blob: d3bae91c4c408b42ab9946a07e00e7021865ff9a [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2012, Google Inc.
4 *
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/base/helpers.h"
42#include "talk/base/logging.h"
43#include "talk/base/stringencode.h"
buildbot@webrtc.org41451d42014-05-03 05:39:45 +000044#include "talk/base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045#include "talk/media/base/constants.h"
46#include "talk/media/base/videocapturer.h"
47#include "talk/session/media/channel.h"
48#include "talk/session/media/channelmanager.h"
49#include "talk/session/media/mediasession.h"
50
51using cricket::ContentInfo;
52using cricket::ContentInfos;
53using cricket::MediaContentDescription;
54using cricket::SessionDescription;
55using cricket::TransportInfo;
56
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057namespace webrtc {
58
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059// Error messages
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000060const char kBundleWithoutRtcpMux[] = "RTCP-MUX must be enabled when BUNDLE "
61 "is enabled.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000062const char kCreateChannelFailed[] = "Failed to create channels.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063const char kInvalidCandidates[] = "Description contains invalid candidates.";
64const char kInvalidSdp[] = "Invalid session description.";
65const char kMlineMismatch[] =
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000066 "Offer and answer descriptions m-lines are not matching. Rejecting answer.";
67const char kPushDownTDFailed[] =
68 "Failed to push down transport description:";
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +000069const char kSdpWithoutDtlsFingerprint[] =
70 "Called with SDP without DTLS fingerprint.";
71const char kSdpWithoutSdesCrypto[] =
72 "Called with SDP without SDES crypto.";
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +000073const char kSdpWithoutIceUfragPwd[] =
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +000074 "Called with SDP without ice-ufrag and ice-pwd.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000075const char kSessionError[] = "Session error code: ";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000076const char kSessionErrorDesc[] = "Session error description: ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000077
78// Compares |answer| against |offer|. Comparision is done
79// for number of m-lines in answer against offer. If matches true will be
80// returned otherwise false.
81static bool VerifyMediaDescriptions(
82 const SessionDescription* answer, const SessionDescription* offer) {
83 if (offer->contents().size() != answer->contents().size())
84 return false;
85
86 for (size_t i = 0; i < offer->contents().size(); ++i) {
87 if ((offer->contents()[i].name) != answer->contents()[i].name) {
88 return false;
89 }
wu@webrtc.org4e393072014-04-07 17:04:35 +000090 const MediaContentDescription* offer_mdesc =
91 static_cast<const MediaContentDescription*>(
92 offer->contents()[i].description);
93 const MediaContentDescription* answer_mdesc =
94 static_cast<const MediaContentDescription*>(
95 answer->contents()[i].description);
96 if (offer_mdesc->type() != answer_mdesc->type()) {
97 return false;
98 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +000099 }
100 return true;
101}
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103// Checks that each non-rejected content has SDES crypto keys or a DTLS
104// fingerprint. Mismatches, such as replying with a DTLS fingerprint to SDES
105// keys, will be caught in Transport negotiation, and backstopped by Channel's
106// |secure_required| check.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000107static bool VerifyCrypto(const SessionDescription* desc,
108 bool dtls_enabled,
109 std::string* error) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110 const ContentInfos& contents = desc->contents();
111 for (size_t index = 0; index < contents.size(); ++index) {
112 const ContentInfo* cinfo = &contents[index];
113 if (cinfo->rejected) {
114 continue;
115 }
116
117 // If the content isn't rejected, crypto must be present.
118 const MediaContentDescription* media =
119 static_cast<const MediaContentDescription*>(cinfo->description);
120 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
121 if (!media || !tinfo) {
122 // Something is not right.
123 LOG(LS_ERROR) << kInvalidSdp;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000124 *error = kInvalidSdp;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000125 return false;
126 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000127 if (dtls_enabled) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000128 if (!tinfo->description.identity_fingerprint) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000129 LOG(LS_WARNING) <<
130 "Session description must have DTLS fingerprint if DTLS enabled.";
131 *error = kSdpWithoutDtlsFingerprint;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000132 return false;
133 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000134 } else {
135 if (media->cryptos().empty()) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000136 LOG(LS_WARNING) <<
137 "Session description must have SDES when DTLS disabled.";
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000138 *error = kSdpWithoutSdesCrypto;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000139 return false;
140 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000141 }
142 }
143
144 return true;
145}
146
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +0000147// Checks that each non-rejected content has ice-ufrag and ice-pwd set.
148static bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
149 const ContentInfos& contents = desc->contents();
150 for (size_t index = 0; index < contents.size(); ++index) {
151 const ContentInfo* cinfo = &contents[index];
152 if (cinfo->rejected) {
153 continue;
154 }
155
156 // If the content isn't rejected, ice-ufrag and ice-pwd must be present.
157 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
158 if (!tinfo) {
159 // Something is not right.
160 LOG(LS_ERROR) << kInvalidSdp;
161 return false;
162 }
163 if (tinfo->description.ice_ufrag.empty() ||
164 tinfo->description.ice_pwd.empty()) {
165 LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
166 return false;
167 }
168 }
169 return true;
170}
171
wu@webrtc.org91053e72013-08-10 07:18:04 +0000172// Forces |sdesc->crypto_required| to the appropriate state based on the
173// current security policy, to ensure a failure occurs if there is an error
174// in crypto negotiation.
175// Called when processing the local session description.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000176static void UpdateSessionDescriptionSecurePolicy(cricket::CryptoType type,
177 SessionDescription* sdesc) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000178 if (!sdesc) {
179 return;
180 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000181
wu@webrtc.org91053e72013-08-10 07:18:04 +0000182 // Updating the |crypto_required_| in MediaContentDescription to the
183 // appropriate state based on the current security policy.
184 for (cricket::ContentInfos::iterator iter = sdesc->contents().begin();
185 iter != sdesc->contents().end(); ++iter) {
186 if (cricket::IsMediaContent(&*iter)) {
187 MediaContentDescription* mdesc =
188 static_cast<MediaContentDescription*> (iter->description);
189 if (mdesc) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000190 mdesc->set_crypto_required(type);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000191 }
192 }
193 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000194}
195
196static bool GetAudioSsrcByTrackId(
197 const SessionDescription* session_description,
198 const std::string& track_id, uint32 *ssrc) {
199 const cricket::ContentInfo* audio_info =
200 cricket::GetFirstAudioContent(session_description);
201 if (!audio_info) {
202 LOG(LS_ERROR) << "Audio not used in this call";
203 return false;
204 }
205
206 const cricket::MediaContentDescription* audio_content =
207 static_cast<const cricket::MediaContentDescription*>(
208 audio_info->description);
209 cricket::StreamParams stream;
210 if (!cricket::GetStreamByIds(audio_content->streams(), "", track_id,
211 &stream)) {
212 return false;
213 }
214 *ssrc = stream.first_ssrc();
215 return true;
216}
217
218static bool GetTrackIdBySsrc(const SessionDescription* session_description,
219 uint32 ssrc, std::string* track_id) {
220 ASSERT(track_id != NULL);
221
222 cricket::StreamParams stream_out;
223 const cricket::ContentInfo* audio_info =
224 cricket::GetFirstAudioContent(session_description);
225 if (!audio_info) {
226 return false;
227 }
228 const cricket::MediaContentDescription* audio_content =
229 static_cast<const cricket::MediaContentDescription*>(
230 audio_info->description);
231
232 if (cricket::GetStreamBySsrc(audio_content->streams(), ssrc, &stream_out)) {
233 *track_id = stream_out.id;
234 return true;
235 }
236
237 const cricket::ContentInfo* video_info =
238 cricket::GetFirstVideoContent(session_description);
239 if (!video_info) {
240 return false;
241 }
242 const cricket::MediaContentDescription* video_content =
243 static_cast<const cricket::MediaContentDescription*>(
244 video_info->description);
245
246 if (cricket::GetStreamBySsrc(video_content->streams(), ssrc, &stream_out)) {
247 *track_id = stream_out.id;
248 return true;
249 }
250 return false;
251}
252
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000253static bool BadSdp(const std::string& source,
254 const std::string& type,
255 const std::string& reason,
256 std::string* err_desc) {
257 std::ostringstream desc;
258 desc << "Failed to set " << source << " " << type << " sdp: " << reason;
259
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000260 if (err_desc) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000261 *err_desc = desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000262 }
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000263 LOG(LS_ERROR) << desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000264 return false;
265}
266
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000267static bool BadSdp(cricket::ContentSource source,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000268 const std::string& type,
269 const std::string& reason,
270 std::string* err_desc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000271 if (source == cricket::CS_LOCAL) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000272 return BadSdp("local", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000273 } else {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000274 return BadSdp("remote", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000275 }
276}
277
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000278static bool BadLocalSdp(const std::string& type,
279 const std::string& reason,
280 std::string* err_desc) {
281 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
282}
283
284static bool BadRemoteSdp(const std::string& type,
285 const std::string& reason,
286 std::string* err_desc) {
287 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
288}
289
290static bool BadOfferSdp(cricket::ContentSource source,
291 const std::string& reason,
292 std::string* err_desc) {
293 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
294}
295
296static bool BadPranswerSdp(cricket::ContentSource source,
297 const std::string& reason,
298 std::string* err_desc) {
299 return BadSdp(source, SessionDescriptionInterface::kPrAnswer,
300 reason, err_desc);
301}
302
303static bool BadAnswerSdp(cricket::ContentSource source,
304 const std::string& reason,
305 std::string* err_desc) {
306 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000307}
308
309#define GET_STRING_OF_STATE(state) \
310 case cricket::BaseSession::state: \
311 result = #state; \
312 break;
313
314static std::string GetStateString(cricket::BaseSession::State state) {
315 std::string result;
316 switch (state) {
317 GET_STRING_OF_STATE(STATE_INIT)
318 GET_STRING_OF_STATE(STATE_SENTINITIATE)
319 GET_STRING_OF_STATE(STATE_RECEIVEDINITIATE)
320 GET_STRING_OF_STATE(STATE_SENTPRACCEPT)
321 GET_STRING_OF_STATE(STATE_SENTACCEPT)
322 GET_STRING_OF_STATE(STATE_RECEIVEDPRACCEPT)
323 GET_STRING_OF_STATE(STATE_RECEIVEDACCEPT)
324 GET_STRING_OF_STATE(STATE_SENTMODIFY)
325 GET_STRING_OF_STATE(STATE_RECEIVEDMODIFY)
326 GET_STRING_OF_STATE(STATE_SENTREJECT)
327 GET_STRING_OF_STATE(STATE_RECEIVEDREJECT)
328 GET_STRING_OF_STATE(STATE_SENTREDIRECT)
329 GET_STRING_OF_STATE(STATE_SENTTERMINATE)
330 GET_STRING_OF_STATE(STATE_RECEIVEDTERMINATE)
331 GET_STRING_OF_STATE(STATE_INPROGRESS)
332 GET_STRING_OF_STATE(STATE_DEINIT)
333 default:
334 ASSERT(false);
335 break;
336 }
337 return result;
338}
339
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000340#define GET_STRING_OF_ERROR_CODE(err) \
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000341 case cricket::BaseSession::err: \
342 result = #err; \
343 break;
344
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000345static std::string GetErrorCodeString(cricket::BaseSession::Error err) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000346 std::string result;
347 switch (err) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000348 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
349 GET_STRING_OF_ERROR_CODE(ERROR_TIME)
350 GET_STRING_OF_ERROR_CODE(ERROR_RESPONSE)
351 GET_STRING_OF_ERROR_CODE(ERROR_NETWORK)
352 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
353 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000354 default:
355 ASSERT(false);
356 break;
357 }
358 return result;
359}
360
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000361static std::string MakeErrorString(const std::string& error,
362 const std::string& desc) {
363 std::ostringstream ret;
364 ret << error << " " << desc;
365 return ret.str();
366}
367
368static std::string MakeTdErrorString(const std::string& desc) {
369 return MakeErrorString(kPushDownTDFailed, desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000370}
371
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000372// Set |option| to the highest-priority value of |key| in the optional
373// constraints if the key is found and has a valid value.
374static void SetOptionFromOptionalConstraint(
375 const MediaConstraintsInterface* constraints,
376 const std::string& key, cricket::Settable<int>* option) {
377 if (!constraints) {
378 return;
379 }
380 std::string string_value;
381 int value;
382 if (constraints->GetOptional().FindFirst(key, &string_value)) {
383 if (talk_base::FromString(string_value, &value)) {
384 option->Set(value);
385 }
386 }
387}
388
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000389// Help class used to remember if a a remote peer has requested ice restart by
390// by sending a description with new ice ufrag and password.
391class IceRestartAnswerLatch {
392 public:
393 IceRestartAnswerLatch() : ice_restart_(false) { }
394
wu@webrtc.org91053e72013-08-10 07:18:04 +0000395 // Returns true if CheckForRemoteIceRestart has been called with a new session
396 // description where ice password and ufrag has changed since last time
397 // Reset() was called.
398 bool Get() const {
399 return ice_restart_;
400 }
401
402 void Reset() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000403 if (ice_restart_) {
404 ice_restart_ = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000405 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000406 }
407
408 void CheckForRemoteIceRestart(
409 const SessionDescriptionInterface* old_desc,
410 const SessionDescriptionInterface* new_desc) {
411 if (!old_desc || new_desc->type() != SessionDescriptionInterface::kOffer) {
412 return;
413 }
414 const SessionDescription* new_sd = new_desc->description();
415 const SessionDescription* old_sd = old_desc->description();
416 const ContentInfos& contents = new_sd->contents();
417 for (size_t index = 0; index < contents.size(); ++index) {
418 const ContentInfo* cinfo = &contents[index];
419 if (cinfo->rejected) {
420 continue;
421 }
422 // If the content isn't rejected, check if ufrag and password has
423 // changed.
424 const cricket::TransportDescription* new_transport_desc =
425 new_sd->GetTransportDescriptionByName(cinfo->name);
426 const cricket::TransportDescription* old_transport_desc =
427 old_sd->GetTransportDescriptionByName(cinfo->name);
428 if (!new_transport_desc || !old_transport_desc) {
429 // No transport description exist. This is not an ice restart.
430 continue;
431 }
432 if (new_transport_desc->ice_pwd != old_transport_desc->ice_pwd &&
433 new_transport_desc->ice_ufrag != old_transport_desc->ice_ufrag) {
434 LOG(LS_INFO) << "Remote peer request ice restart.";
435 ice_restart_ = true;
436 break;
437 }
438 }
439 }
440
441 private:
442 bool ice_restart_;
443};
444
wu@webrtc.org91053e72013-08-10 07:18:04 +0000445WebRtcSession::WebRtcSession(
446 cricket::ChannelManager* channel_manager,
447 talk_base::Thread* signaling_thread,
448 talk_base::Thread* worker_thread,
449 cricket::PortAllocator* port_allocator,
450 MediaStreamSignaling* mediastream_signaling)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000451 : cricket::BaseSession(signaling_thread, worker_thread, port_allocator,
452 talk_base::ToString(talk_base::CreateRandomId64() &
453 LLONG_MAX),
454 cricket::NS_JINGLE_RTP, false),
455 // RFC 3264: The numeric value of the session id and version in the
456 // o line MUST be representable with a "64 bit signed integer".
457 // Due to this constraint session id |sid_| is max limited to LLONG_MAX.
458 channel_manager_(channel_manager),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000459 mediastream_signaling_(mediastream_signaling),
460 ice_observer_(NULL),
461 ice_connection_state_(PeerConnectionInterface::kIceConnectionNew),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000462 older_version_remote_peer_(false),
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000463 dtls_enabled_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000464 data_channel_type_(cricket::DCT_NONE),
465 ice_restart_latch_(new IceRestartAnswerLatch) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000466}
467
468WebRtcSession::~WebRtcSession() {
469 if (voice_channel_.get()) {
470 SignalVoiceChannelDestroyed();
471 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
472 }
473 if (video_channel_.get()) {
474 SignalVideoChannelDestroyed();
475 channel_manager_->DestroyVideoChannel(video_channel_.release());
476 }
477 if (data_channel_.get()) {
478 SignalDataChannelDestroyed();
479 channel_manager_->DestroyDataChannel(data_channel_.release());
480 }
481 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
482 delete saved_candidates_[i];
483 }
484 delete identity();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000485}
486
wu@webrtc.org91053e72013-08-10 07:18:04 +0000487bool WebRtcSession::Initialize(
wu@webrtc.org97077a32013-10-25 21:18:33 +0000488 const PeerConnectionFactoryInterface::Options& options,
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000489 const MediaConstraintsInterface* constraints,
490 DTLSIdentityServiceInterface* dtls_identity_service,
491 PeerConnectionInterface::IceTransportsType ice_transport) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000492 // TODO(perkj): Take |constraints| into consideration. Return false if not all
493 // mandatory constraints can be fulfilled. Note that |constraints|
494 // can be null.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000495 bool value;
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000496
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000497 if (options.disable_encryption) {
498 dtls_enabled_ = false;
499 } else {
500 // Enable DTLS by default if |dtls_identity_service| is valid.
501 dtls_enabled_ = (dtls_identity_service != NULL);
502 // |constraints| can override the default |dtls_enabled_| value.
503 if (FindConstraint(
504 constraints,
505 MediaConstraintsInterface::kEnableDtlsSrtp,
506 &value, NULL)) {
507 dtls_enabled_ = value;
508 }
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000509 }
510
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000511 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000512 // It takes precendence over the disable_sctp_data_channels
513 // PeerConnectionFactoryInterface::Options.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000514 if (FindConstraint(
515 constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
516 &value, NULL) && value) {
517 LOG(LS_INFO) << "Allowing RTP data engine.";
518 data_channel_type_ = cricket::DCT_RTP;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000519 } else {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000520 // DTLS has to be enabled to use SCTP.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000521 if (!options.disable_sctp_data_channels && dtls_enabled_) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000522 LOG(LS_INFO) << "Allowing SCTP data engine.";
523 data_channel_type_ = cricket::DCT_SCTP;
524 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000525 }
526 if (data_channel_type_ != cricket::DCT_NONE) {
527 mediastream_signaling_->SetDataChannelFactory(this);
528 }
529
wu@webrtc.orgde305012013-10-31 15:40:38 +0000530 // Find DSCP constraint.
531 if (FindConstraint(
532 constraints,
533 MediaConstraintsInterface::kEnableDscp,
534 &value, NULL)) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +0000535 audio_options_.dscp.Set(value);
536 video_options_.dscp.Set(value);
537 }
538
539 // Find Suspend Below Min Bitrate constraint.
540 if (FindConstraint(
541 constraints,
542 MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate,
543 &value,
544 NULL)) {
545 video_options_.suspend_below_min_bitrate.Set(value);
wu@webrtc.orgde305012013-10-31 15:40:38 +0000546 }
547
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000548 if (FindConstraint(
549 constraints,
550 MediaConstraintsInterface::kSkipEncodingUnusedStreams,
551 &value,
552 NULL)) {
553 video_options_.skip_encoding_unused_streams.Set(value);
554 }
555
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000556 SetOptionFromOptionalConstraint(constraints,
557 MediaConstraintsInterface::kScreencastMinBitrate,
558 &video_options_.screencast_min_bitrate);
559
560 // Find constraints for cpu overuse detection.
561 SetOptionFromOptionalConstraint(constraints,
562 MediaConstraintsInterface::kCpuUnderuseThreshold,
563 &video_options_.cpu_underuse_threshold);
564 SetOptionFromOptionalConstraint(constraints,
565 MediaConstraintsInterface::kCpuOveruseThreshold,
566 &video_options_.cpu_overuse_threshold);
567
568 if (FindConstraint(
569 constraints,
570 MediaConstraintsInterface::kCpuOveruseDetection,
571 &value,
572 NULL)) {
573 video_options_.cpu_overuse_detection.Set(value);
574 }
575 if (FindConstraint(
576 constraints,
577 MediaConstraintsInterface::kCpuOveruseEncodeUsage,
578 &value,
579 NULL)) {
580 video_options_.cpu_overuse_encode_usage.Set(value);
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000581 }
582
583 // Find improved wifi bwe constraint.
584 if (FindConstraint(
585 constraints,
586 MediaConstraintsInterface::kImprovedWifiBwe,
587 &value,
588 NULL)) {
589 video_options_.use_improved_wifi_bandwidth_estimator.Set(value);
buildbot@webrtc.orgff6a3d92014-05-08 16:16:41 +0000590 } else {
591 // Enable by default if the constraint is not set.
592 video_options_.use_improved_wifi_bandwidth_estimator.Set(true);
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000593 }
594
wu@webrtc.orgcfe5e9c2014-03-27 17:03:58 +0000595 if (FindConstraint(
596 constraints,
597 MediaConstraintsInterface::kHighStartBitrate,
598 &value,
599 NULL)) {
600 video_options_.video_start_bitrate.Set(cricket::kHighStartBitrate);
601 }
602
603 if (FindConstraint(
604 constraints,
605 MediaConstraintsInterface::kVeryHighBitrate,
606 &value,
607 NULL)) {
608 video_options_.video_highest_bitrate.Set(
609 cricket::VideoOptions::VERY_HIGH);
610 } else if (FindConstraint(
611 constraints,
612 MediaConstraintsInterface::kHighBitrate,
613 &value,
614 NULL)) {
615 video_options_.video_highest_bitrate.Set(
616 cricket::VideoOptions::HIGH);
617 }
618
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000619 const cricket::VideoCodec default_codec(
620 JsepSessionDescription::kDefaultVideoCodecId,
621 JsepSessionDescription::kDefaultVideoCodecName,
622 JsepSessionDescription::kMaxVideoCodecWidth,
623 JsepSessionDescription::kMaxVideoCodecHeight,
624 JsepSessionDescription::kDefaultVideoCodecFramerate,
625 JsepSessionDescription::kDefaultVideoCodecPreference);
626 channel_manager_->SetDefaultVideoEncoderConfig(
627 cricket::VideoEncoderConfig(default_codec));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000628
629 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
630 signaling_thread(),
631 channel_manager_,
632 mediastream_signaling_,
633 dtls_identity_service,
634 this,
635 id(),
636 data_channel_type_,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000637 dtls_enabled_));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000638
639 webrtc_session_desc_factory_->SignalIdentityReady.connect(
640 this, &WebRtcSession::OnIdentityReady);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000641
wu@webrtc.org97077a32013-10-25 21:18:33 +0000642 if (options.disable_encryption) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000643 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000644 }
645
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000646 return true;
647}
648
649void WebRtcSession::Terminate() {
650 SetState(STATE_RECEIVEDTERMINATE);
651 RemoveUnusedChannelsAndTransports(NULL);
652 ASSERT(voice_channel_.get() == NULL);
653 ASSERT(video_channel_.get() == NULL);
654 ASSERT(data_channel_.get() == NULL);
655}
656
657bool WebRtcSession::StartCandidatesAllocation() {
658 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
659 // from TransportProxy to start gathering ice candidates.
660 SpeculativelyConnectAllTransportChannels();
661 if (!saved_candidates_.empty()) {
662 // If there are saved candidates which arrived before local description is
663 // set, copy those to remote description.
664 CopySavedCandidates(remote_desc_.get());
665 }
666 // Push remote candidates present in remote description to transport channels.
667 UseCandidatesInSessionDescription(remote_desc_.get());
668 return true;
669}
670
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000671void WebRtcSession::SetSdesPolicy(cricket::SecurePolicy secure_policy) {
672 webrtc_session_desc_factory_->SetSdesPolicy(secure_policy);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000673}
674
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000675cricket::SecurePolicy WebRtcSession::SdesPolicy() const {
676 return webrtc_session_desc_factory_->SdesPolicy();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000677}
678
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000679bool WebRtcSession::GetSslRole(talk_base::SSLRole* role) {
680 if (local_description() == NULL || remote_description() == NULL) {
681 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
682 << "SSL Role of the session.";
683 return false;
684 }
685
686 // TODO(mallinath) - Return role of each transport, as role may differ from
687 // one another.
688 // In current implementaion we just return the role of first transport in the
689 // transport map.
690 for (cricket::TransportMap::const_iterator iter = transport_proxies().begin();
691 iter != transport_proxies().end(); ++iter) {
692 if (iter->second->impl()) {
693 return iter->second->impl()->GetSslRole(role);
694 }
695 }
696 return false;
697}
698
wu@webrtc.org91053e72013-08-10 07:18:04 +0000699void WebRtcSession::CreateOffer(CreateSessionDescriptionObserver* observer,
700 const MediaConstraintsInterface* constraints) {
701 webrtc_session_desc_factory_->CreateOffer(observer, constraints);
702}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000703
wu@webrtc.org91053e72013-08-10 07:18:04 +0000704void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
705 const MediaConstraintsInterface* constraints) {
706 webrtc_session_desc_factory_->CreateAnswer(observer, constraints);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707}
708
709bool WebRtcSession::SetLocalDescription(SessionDescriptionInterface* desc,
710 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000711 // Takes the ownership of |desc| regardless of the result.
712 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
713
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000714 // Validate SDP.
715 if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
716 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000717 }
718
719 // Update the initiator flag if this session is the initiator.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000720 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000721 if (state() == STATE_INIT && action == kOffer) {
722 set_initiator(true);
723 }
724
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000725 cricket::SecurePolicy sdes_policy =
726 webrtc_session_desc_factory_->SdesPolicy();
727 cricket::CryptoType crypto_required = dtls_enabled_ ?
728 cricket::CT_DTLS : (sdes_policy == cricket::SEC_REQUIRED ?
729 cricket::CT_SDES : cricket::CT_NONE);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730 // Update the MediaContentDescription crypto settings as per the policy set.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000731 UpdateSessionDescriptionSecurePolicy(crypto_required, desc->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000732
733 set_local_description(desc->description()->Copy());
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000734 local_desc_.reset(desc_temp.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000735
736 // Transport and Media channels will be created only when offer is set.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000737 if (action == kOffer && !CreateChannels(local_desc_->description())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000738 // TODO(mallinath) - Handle CreateChannel failure, as new local description
739 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000740 return BadLocalSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000741 }
742
743 // Remove channel and transport proxies, if MediaContentDescription is
744 // rejected.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000745 RemoveUnusedChannelsAndTransports(local_desc_->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000746
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000747 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000748 return false;
749 }
750 // Kick starting the ice candidates allocation.
751 StartCandidatesAllocation();
752
753 // Update state and SSRC of local MediaStreams and DataChannels based on the
754 // local session description.
755 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
756
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000757 talk_base::SSLRole role;
758 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
759 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
760 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000761 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000762 return BadLocalSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000763 }
764 return true;
765}
766
767bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
768 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000769 // Takes the ownership of |desc| regardless of the result.
770 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
771
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000772 // Validate SDP.
773 if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
774 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000775 }
776
777 // Transport and Media channels will be created only when offer is set.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000778 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000779 if (action == kOffer && !CreateChannels(desc->description())) {
780 // TODO(mallinath) - Handle CreateChannel failure, as new local description
781 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000782 return BadRemoteSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000783 }
784
785 // Remove channel and transport proxies, if MediaContentDescription is
786 // rejected.
787 RemoveUnusedChannelsAndTransports(desc->description());
788
789 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
790 // is called.
791 set_remote_description(desc->description()->Copy());
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000792 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000793 return false;
794 }
795
796 // Update remote MediaStreams.
797 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
798 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000799 return BadRemoteSdp(desc->type(), kInvalidCandidates, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000800 }
801
802 // Copy all saved candidates.
803 CopySavedCandidates(desc);
804 // We retain all received candidates.
wu@webrtc.org91053e72013-08-10 07:18:04 +0000805 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
806 remote_desc_.get(), desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807 // Check if this new SessionDescription contains new ice ufrag and password
808 // that indicates the remote peer requests ice restart.
809 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(),
810 desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000811 remote_desc_.reset(desc_temp.release());
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000812
813 talk_base::SSLRole role;
814 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
815 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
816 }
817
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000818 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000819 return BadRemoteSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000820 }
821 return true;
822}
823
824bool WebRtcSession::UpdateSessionState(
825 Action action, cricket::ContentSource source,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826 std::string* err_desc) {
827 // If there's already a pending error then no state transition should happen.
828 // But all call-sites should be verifying this before calling us!
829 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000830 std::string td_err;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831 if (action == kOffer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000832 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
833 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000834 }
835 SetState(source == cricket::CS_LOCAL ?
836 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
837 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000838 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000839 }
840 } else if (action == kPrAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000841 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
842 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000843 }
844 EnableChannels();
845 SetState(source == cricket::CS_LOCAL ?
846 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
847 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000848 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000849 }
850 } else if (action == kAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000851 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
852 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000853 }
854 MaybeEnableMuxingSupport();
855 EnableChannels();
856 SetState(source == cricket::CS_LOCAL ?
857 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
858 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000859 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000860 }
861 }
862 return true;
863}
864
865WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
866 if (type == SessionDescriptionInterface::kOffer) {
867 return WebRtcSession::kOffer;
868 } else if (type == SessionDescriptionInterface::kPrAnswer) {
869 return WebRtcSession::kPrAnswer;
870 } else if (type == SessionDescriptionInterface::kAnswer) {
871 return WebRtcSession::kAnswer;
872 }
873 ASSERT(false && "unknown action type");
874 return WebRtcSession::kOffer;
875}
876
877bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
878 if (state() == STATE_INIT) {
879 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
880 << "without any offer (local or remote) "
881 << "session description.";
882 return false;
883 }
884
885 if (!candidate) {
886 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
887 return false;
888 }
889
buildbot@webrtc.org61c1b8e2014-04-09 06:06:38 +0000890 cricket::TransportProxy* transport_proxy = NULL;
891 if (remote_description()) {
892 size_t mediacontent_index =
893 static_cast<size_t>(candidate->sdp_mline_index());
894 size_t remote_content_size =
895 BaseSession::remote_description()->contents().size();
896 if (mediacontent_index >= remote_content_size) {
897 LOG(LS_ERROR)
898 << "ProcessIceMessage: Invalid candidate media index.";
899 return false;
900 }
901
902 cricket::ContentInfo content =
903 BaseSession::remote_description()->contents()[mediacontent_index];
904 transport_proxy = GetTransportProxy(content.name);
905 }
906
907 // We need to check the local/remote description for the Transport instead of
908 // the session, because a new Transport added during renegotiation may have
909 // them unset while the session has them set from the previou negotiation. Not
910 // doing so may trigger the auto generation of transport description and mess
911 // up DTLS identity information, ICE credential, etc.
912 if (!transport_proxy || !(transport_proxy->local_description_set() &&
913 transport_proxy->remote_description_set())) {
914 LOG(LS_INFO) << "ProcessIceMessage: Local/Remote description not set "
915 << "on the Transport, save the candidate for later use.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000916 saved_candidates_.push_back(
917 new JsepIceCandidate(candidate->sdp_mid(), candidate->sdp_mline_index(),
918 candidate->candidate()));
919 return true;
920 }
921
922 // Add this candidate to the remote session description.
923 if (!remote_desc_->AddCandidate(candidate)) {
924 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
925 return false;
926 }
927
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000928 return UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000929}
930
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000931bool WebRtcSession::UpdateIce(PeerConnectionInterface::IceTransportsType type) {
932 return false;
933}
934
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935bool WebRtcSession::GetTrackIdBySsrc(uint32 ssrc, std::string* id) {
936 if (GetLocalTrackId(ssrc, id)) {
937 if (GetRemoteTrackId(ssrc, id)) {
938 LOG(LS_WARNING) << "SSRC " << ssrc
939 << " exists in both local and remote descriptions";
940 return true; // We return the remote track id.
941 }
942 return true;
943 } else {
944 return GetRemoteTrackId(ssrc, id);
945 }
946}
947
948bool WebRtcSession::GetLocalTrackId(uint32 ssrc, std::string* track_id) {
949 if (!BaseSession::local_description())
950 return false;
951 return webrtc::GetTrackIdBySsrc(
952 BaseSession::local_description(), ssrc, track_id);
953}
954
955bool WebRtcSession::GetRemoteTrackId(uint32 ssrc, std::string* track_id) {
956 if (!BaseSession::remote_description())
957 return false;
958 return webrtc::GetTrackIdBySsrc(
959 BaseSession::remote_description(), ssrc, track_id);
960}
961
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000962std::string WebRtcSession::BadStateErrMsg(State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963 std::ostringstream desc;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000964 desc << "Called in wrong state: " << GetStateString(state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000965 return desc.str();
966}
967
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000968void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable,
969 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000970 ASSERT(signaling_thread()->IsCurrent());
971 if (!voice_channel_) {
972 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
973 return;
974 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000975 if (!voice_channel_->SetRemoteRenderer(ssrc, renderer)) {
976 // SetRenderer() can fail if the ssrc does not match any playout channel.
977 LOG(LS_ERROR) << "SetAudioPlayout: ssrc is incorrect: " << ssrc;
978 return;
979 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000980 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
981 // Allow that SetOutputScaling fail if |enable| is false but assert
982 // otherwise. This in the normal case when the underlying media channel has
983 // already been deleted.
984 ASSERT(enable == false);
985 }
986}
987
988void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000989 const cricket::AudioOptions& options,
990 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000991 ASSERT(signaling_thread()->IsCurrent());
992 if (!voice_channel_) {
993 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
994 return;
995 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000996 if (!voice_channel_->SetLocalRenderer(ssrc, renderer)) {
997 // SetRenderer() can fail if the ssrc does not match any send channel.
998 LOG(LS_ERROR) << "SetAudioSend: ssrc is incorrect: " << ssrc;
999 return;
1000 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001001 if (!voice_channel_->MuteStream(ssrc, !enable)) {
1002 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1003 // This in the normal case when the underlying media channel has already
1004 // been deleted.
1005 ASSERT(enable == false);
1006 return;
1007 }
1008 if (enable)
1009 voice_channel_->SetChannelOptions(options);
1010}
1011
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001012void WebRtcSession::SetAudioPlayoutVolume(uint32 ssrc, double volume) {
1013 ASSERT(signaling_thread()->IsCurrent());
1014 ASSERT(volume >= 0 && volume <= 10);
1015 if (!voice_channel_) {
1016 LOG(LS_ERROR) << "SetAudioPlayoutVolume: No audio channel exists.";
1017 return;
1018 }
1019
1020 if (!voice_channel_->SetOutputScaling(ssrc, volume, volume))
1021 ASSERT(false);
1022}
1023
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001024bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
1025 cricket::VideoCapturer* camera) {
1026 ASSERT(signaling_thread()->IsCurrent());
1027
1028 if (!video_channel_.get()) {
1029 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
1030 // support video.
1031 LOG(LS_WARNING) << "Video not used in this call.";
1032 return false;
1033 }
1034 if (!video_channel_->SetCapturer(ssrc, camera)) {
1035 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
1036 // This in the normal case when the underlying media channel has already
1037 // been deleted.
1038 ASSERT(camera == NULL);
1039 return false;
1040 }
1041 return true;
1042}
1043
1044void WebRtcSession::SetVideoPlayout(uint32 ssrc,
1045 bool enable,
1046 cricket::VideoRenderer* renderer) {
1047 ASSERT(signaling_thread()->IsCurrent());
1048 if (!video_channel_) {
1049 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
1050 return;
1051 }
1052 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
1053 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
1054 // This in the normal case when the underlying media channel has already
1055 // been deleted.
1056 ASSERT(renderer == NULL);
1057 }
1058}
1059
1060void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
1061 const cricket::VideoOptions* options) {
1062 ASSERT(signaling_thread()->IsCurrent());
1063 if (!video_channel_) {
1064 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
1065 return;
1066 }
1067 if (!video_channel_->MuteStream(ssrc, !enable)) {
1068 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1069 // This in the normal case when the underlying media channel has already
1070 // been deleted.
1071 ASSERT(enable == false);
1072 return;
1073 }
1074 if (enable && options)
1075 video_channel_->SetChannelOptions(*options);
1076}
1077
1078bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
1079 ASSERT(signaling_thread()->IsCurrent());
1080 if (!voice_channel_) {
1081 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
1082 return false;
1083 }
1084 uint32 send_ssrc = 0;
1085 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
1086 // exists.
1087 if (!GetAudioSsrcByTrackId(BaseSession::local_description(), track_id,
1088 &send_ssrc)) {
1089 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1090 return false;
1091 }
1092 return voice_channel_->CanInsertDtmf();
1093}
1094
1095bool WebRtcSession::InsertDtmf(const std::string& track_id,
1096 int code, int duration) {
1097 ASSERT(signaling_thread()->IsCurrent());
1098 if (!voice_channel_) {
1099 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1100 return false;
1101 }
1102 uint32 send_ssrc = 0;
1103 if (!VERIFY(GetAudioSsrcByTrackId(BaseSession::local_description(),
1104 track_id, &send_ssrc))) {
1105 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1106 return false;
1107 }
1108 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1109 cricket::DF_SEND)) {
1110 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1111 return false;
1112 }
1113 return true;
1114}
1115
1116sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1117 return &SignalVoiceChannelDestroyed;
1118}
1119
wu@webrtc.org78187522013-10-07 23:32:02 +00001120bool WebRtcSession::SendData(const cricket::SendDataParams& params,
1121 const talk_base::Buffer& payload,
1122 cricket::SendDataResult* result) {
1123 if (!data_channel_.get()) {
1124 LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
1125 return false;
1126 }
1127 return data_channel_->SendData(params, payload, result);
1128}
1129
1130bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
1131 if (!data_channel_.get()) {
1132 LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
1133 return false;
1134 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001135 data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
1136 &DataChannel::OnChannelReady);
1137 data_channel_->SignalDataReceived.connect(webrtc_data_channel,
1138 &DataChannel::OnDataReceived);
wu@webrtc.org78187522013-10-07 23:32:02 +00001139 return true;
1140}
1141
1142void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001143 if (!data_channel_.get()) {
1144 LOG(LS_ERROR) << "DisconnectDataChannel called when data_channel_ is NULL.";
1145 return;
1146 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001147 data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
1148 data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
1149}
1150
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001151void WebRtcSession::AddSctpDataStream(uint32 sid) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001152 if (!data_channel_.get()) {
1153 LOG(LS_ERROR) << "AddDataChannelStreams called when data_channel_ is NULL.";
1154 return;
1155 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001156 data_channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(sid));
1157 data_channel_->AddSendStream(cricket::StreamParams::CreateLegacy(sid));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001158}
1159
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001160void WebRtcSession::RemoveSctpDataStream(uint32 sid) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001161 if (!data_channel_.get()) {
1162 LOG(LS_ERROR) << "RemoveDataChannelStreams called when data_channel_ is "
1163 << "NULL.";
1164 return;
1165 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001166 data_channel_->RemoveRecvStream(sid);
1167 data_channel_->RemoveSendStream(sid);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001168}
1169
wu@webrtc.org07a6fbe2013-11-04 18:41:34 +00001170bool WebRtcSession::ReadyToSendData() const {
1171 return data_channel_.get() && data_channel_->ready_to_send_data();
1172}
1173
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001174talk_base::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
wu@webrtc.org78187522013-10-07 23:32:02 +00001175 const std::string& label,
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001176 const InternalDataChannelInit* config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001177 if (state() == STATE_RECEIVEDTERMINATE) {
1178 return NULL;
1179 }
1180 if (data_channel_type_ == cricket::DCT_NONE) {
1181 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1182 return NULL;
1183 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001184 InternalDataChannelInit new_config =
1185 config ? (*config) : InternalDataChannelInit();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001186 if (data_channel_type_ == cricket::DCT_SCTP) {
1187 if (new_config.id < 0) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001188 talk_base::SSLRole role;
1189 if (GetSslRole(&role) &&
1190 !mediastream_signaling_->AllocateSctpSid(role, &new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1192 return NULL;
1193 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001194 } else if (!mediastream_signaling_->IsSctpSidAvailable(new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001195 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1196 << "because the id is already in use or out of range.";
1197 return NULL;
1198 }
1199 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001200
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001201 talk_base::scoped_refptr<DataChannel> channel(DataChannel::Create(
1202 this, data_channel_type_, label, new_config));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001203 if (channel && !mediastream_signaling_->AddDataChannel(channel))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001204 return NULL;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001205
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001206 return channel;
1207}
1208
1209cricket::DataChannelType WebRtcSession::data_channel_type() const {
1210 return data_channel_type_;
1211}
1212
wu@webrtc.org91053e72013-08-10 07:18:04 +00001213bool WebRtcSession::IceRestartPending() const {
1214 return ice_restart_latch_->Get();
1215}
1216
1217void WebRtcSession::ResetIceRestartLatch() {
1218 ice_restart_latch_->Reset();
1219}
1220
1221void WebRtcSession::OnIdentityReady(talk_base::SSLIdentity* identity) {
1222 SetIdentity(identity);
1223}
1224
1225bool WebRtcSession::waiting_for_identity() const {
1226 return webrtc_session_desc_factory_->waiting_for_identity();
1227}
1228
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001229void WebRtcSession::SetIceConnectionState(
1230 PeerConnectionInterface::IceConnectionState state) {
1231 if (ice_connection_state_ == state) {
1232 return;
1233 }
1234
1235 // ASSERT that the requested transition is allowed. Note that
1236 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1237 // within PeerConnection). This switch statement should compile away when
1238 // ASSERTs are disabled.
1239 switch (ice_connection_state_) {
1240 case PeerConnectionInterface::kIceConnectionNew:
1241 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1242 break;
1243 case PeerConnectionInterface::kIceConnectionChecking:
1244 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1245 state == PeerConnectionInterface::kIceConnectionConnected);
1246 break;
1247 case PeerConnectionInterface::kIceConnectionConnected:
1248 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1249 state == PeerConnectionInterface::kIceConnectionChecking ||
1250 state == PeerConnectionInterface::kIceConnectionCompleted);
1251 break;
1252 case PeerConnectionInterface::kIceConnectionCompleted:
1253 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1254 state == PeerConnectionInterface::kIceConnectionDisconnected);
1255 break;
1256 case PeerConnectionInterface::kIceConnectionFailed:
1257 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1258 break;
1259 case PeerConnectionInterface::kIceConnectionDisconnected:
1260 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1261 state == PeerConnectionInterface::kIceConnectionConnected ||
1262 state == PeerConnectionInterface::kIceConnectionCompleted ||
1263 state == PeerConnectionInterface::kIceConnectionFailed);
1264 break;
1265 case PeerConnectionInterface::kIceConnectionClosed:
1266 ASSERT(false);
1267 break;
1268 default:
1269 ASSERT(false);
1270 break;
1271 }
1272
1273 ice_connection_state_ = state;
1274 if (ice_observer_) {
1275 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1276 }
1277}
1278
1279void WebRtcSession::OnTransportRequestSignaling(
1280 cricket::Transport* transport) {
1281 ASSERT(signaling_thread()->IsCurrent());
1282 transport->OnSignalingReady();
1283 if (ice_observer_) {
1284 ice_observer_->OnIceGatheringChange(
1285 PeerConnectionInterface::kIceGatheringGathering);
1286 }
1287}
1288
1289void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1290 ASSERT(signaling_thread()->IsCurrent());
1291 // start monitoring for the write state of the transport.
1292 OnTransportWritable(transport);
1293}
1294
1295void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1296 ASSERT(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297 if (transport->all_channels_writable()) {
henrike@webrtc.org05376342014-03-10 15:53:12 +00001298 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299 } else if (transport->HasChannels()) {
1300 // If the current state is Connected or Completed, then there were writable
1301 // channels but now there are not, so the next state must be Disconnected.
1302 if (ice_connection_state_ ==
1303 PeerConnectionInterface::kIceConnectionConnected ||
1304 ice_connection_state_ ==
1305 PeerConnectionInterface::kIceConnectionCompleted) {
1306 SetIceConnectionState(
1307 PeerConnectionInterface::kIceConnectionDisconnected);
1308 }
1309 }
1310}
1311
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001312void WebRtcSession::OnTransportCompleted(cricket::Transport* transport) {
1313 ASSERT(signaling_thread()->IsCurrent());
1314 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
1315}
1316
1317void WebRtcSession::OnTransportFailed(cricket::Transport* transport) {
1318 ASSERT(signaling_thread()->IsCurrent());
1319 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
1320}
1321
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001322void WebRtcSession::OnTransportProxyCandidatesReady(
1323 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1324 ASSERT(signaling_thread()->IsCurrent());
1325 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1326}
1327
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328void WebRtcSession::OnCandidatesAllocationDone() {
1329 ASSERT(signaling_thread()->IsCurrent());
1330 if (ice_observer_) {
1331 ice_observer_->OnIceGatheringChange(
1332 PeerConnectionInterface::kIceGatheringComplete);
1333 ice_observer_->OnIceComplete();
1334 }
1335}
1336
1337// Enabling voice and video channel.
1338void WebRtcSession::EnableChannels() {
1339 if (voice_channel_ && !voice_channel_->enabled())
1340 voice_channel_->Enable(true);
1341
1342 if (video_channel_ && !video_channel_->enabled())
1343 video_channel_->Enable(true);
1344
1345 if (data_channel_.get() && !data_channel_->enabled())
1346 data_channel_->Enable(true);
1347}
1348
1349void WebRtcSession::ProcessNewLocalCandidate(
1350 const std::string& content_name,
1351 const cricket::Candidates& candidates) {
1352 int sdp_mline_index;
1353 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1354 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1355 << content_name << " not found";
1356 return;
1357 }
1358
1359 for (cricket::Candidates::const_iterator citer = candidates.begin();
1360 citer != candidates.end(); ++citer) {
1361 // Use content_name as the candidate media id.
1362 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1363 if (ice_observer_) {
1364 ice_observer_->OnIceCandidate(&candidate);
1365 }
1366 if (local_desc_) {
1367 local_desc_->AddCandidate(&candidate);
1368 }
1369 }
1370}
1371
1372// Returns the media index for a local ice candidate given the content name.
1373bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1374 int* sdp_mline_index) {
1375 if (!BaseSession::local_description() || !sdp_mline_index)
1376 return false;
1377
1378 bool content_found = false;
1379 const ContentInfos& contents = BaseSession::local_description()->contents();
1380 for (size_t index = 0; index < contents.size(); ++index) {
1381 if (contents[index].name == content_name) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001382 *sdp_mline_index = static_cast<int>(index);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001383 content_found = true;
1384 break;
1385 }
1386 }
1387 return content_found;
1388}
1389
1390bool WebRtcSession::UseCandidatesInSessionDescription(
1391 const SessionDescriptionInterface* remote_desc) {
1392 if (!remote_desc)
1393 return true;
1394 bool ret = true;
1395 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1396 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1397 for (size_t n = 0; n < candidates->count(); ++n) {
1398 ret = UseCandidate(candidates->at(n));
1399 if (!ret)
1400 break;
1401 }
1402 }
1403 return ret;
1404}
1405
1406bool WebRtcSession::UseCandidate(
1407 const IceCandidateInterface* candidate) {
1408
1409 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
1410 size_t remote_content_size =
1411 BaseSession::remote_description()->contents().size();
1412 if (mediacontent_index >= remote_content_size) {
1413 LOG(LS_ERROR)
1414 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1415 return false;
1416 }
1417
1418 cricket::ContentInfo content =
1419 BaseSession::remote_description()->contents()[mediacontent_index];
1420 std::vector<cricket::Candidate> candidates;
1421 candidates.push_back(candidate->candidate());
1422 // Invoking BaseSession method to handle remote candidates.
1423 std::string error;
1424 if (OnRemoteCandidates(content.name, candidates, &error)) {
1425 // Candidates successfully submitted for checking.
1426 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1427 ice_connection_state_ ==
1428 PeerConnectionInterface::kIceConnectionDisconnected) {
1429 // If state is New, then the session has just gotten its first remote ICE
1430 // candidates, so go to Checking.
1431 // If state is Disconnected, the session is re-using old candidates or
1432 // receiving additional ones, so go to Checking.
1433 // If state is Connected, stay Connected.
1434 // TODO(bemasc): If state is Connected, and the new candidates are for a
1435 // newly added transport, then the state actually _should_ move to
1436 // checking. Add a way to distinguish that case.
1437 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1438 }
1439 // TODO(bemasc): If state is Completed, go back to Connected.
1440 } else {
fischman@webrtc.org4f2bd682014-03-28 18:13:34 +00001441 if (!error.empty()) {
1442 LOG(LS_WARNING) << error;
1443 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001444 }
1445 return true;
1446}
1447
1448void WebRtcSession::RemoveUnusedChannelsAndTransports(
1449 const SessionDescription* desc) {
1450 const cricket::ContentInfo* voice_info =
1451 cricket::GetFirstAudioContent(desc);
1452 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1453 mediastream_signaling_->OnAudioChannelClose();
1454 SignalVoiceChannelDestroyed();
1455 const std::string content_name = voice_channel_->content_name();
1456 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
1457 DestroyTransportProxy(content_name);
1458 }
1459
1460 const cricket::ContentInfo* video_info =
1461 cricket::GetFirstVideoContent(desc);
1462 if ((!video_info || video_info->rejected) && video_channel_) {
1463 mediastream_signaling_->OnVideoChannelClose();
1464 SignalVideoChannelDestroyed();
1465 const std::string content_name = video_channel_->content_name();
1466 channel_manager_->DestroyVideoChannel(video_channel_.release());
1467 DestroyTransportProxy(content_name);
1468 }
1469
1470 const cricket::ContentInfo* data_info =
1471 cricket::GetFirstDataContent(desc);
1472 if ((!data_info || data_info->rejected) && data_channel_) {
1473 mediastream_signaling_->OnDataChannelClose();
1474 SignalDataChannelDestroyed();
1475 const std::string content_name = data_channel_->content_name();
1476 channel_manager_->DestroyDataChannel(data_channel_.release());
1477 DestroyTransportProxy(content_name);
1478 }
1479}
1480
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001481// TODO(mallinath) - Add a correct error code if the channels are not creatued
1482// due to BUNDLE is enabled but rtcp-mux is disabled.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001483bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
1484 // Disabling the BUNDLE flag in PortAllocator if offer disabled it.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001485 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1486 if (state() == STATE_INIT && !bundle_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001487 port_allocator()->set_flags(port_allocator()->flags() &
1488 ~cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1489 }
1490
1491 // Creating the media channels and transport proxies.
1492 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1493 if (voice && !voice->rejected && !voice_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001494 if (!CreateVoiceChannel(voice)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001495 LOG(LS_ERROR) << "Failed to create voice channel.";
1496 return false;
1497 }
1498 }
1499
1500 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1501 if (video && !video->rejected && !video_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001502 if (!CreateVideoChannel(video)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001503 LOG(LS_ERROR) << "Failed to create video channel.";
1504 return false;
1505 }
1506 }
1507
1508 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1509 if (data_channel_type_ != cricket::DCT_NONE &&
1510 data && !data->rejected && !data_channel_.get()) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001511 if (!CreateDataChannel(data)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001512 LOG(LS_ERROR) << "Failed to create data channel.";
1513 return false;
1514 }
1515 }
1516
1517 return true;
1518}
1519
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001520bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001521 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001522 this, content->name, true));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001523 if (!voice_channel_.get())
1524 return false;
1525
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001526 voice_channel_->SetChannelOptions(audio_options_);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001527 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001528}
1529
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001530bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001531 video_channel_.reset(channel_manager_->CreateVideoChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001532 this, content->name, true, voice_channel_.get()));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001533 if (!video_channel_.get())
1534 return false;
1535
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001536 video_channel_->SetChannelOptions(video_options_);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001537 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001538}
1539
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001540bool WebRtcSession::CreateDataChannel(const cricket::ContentInfo* content) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001541 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001542 data_channel_.reset(channel_manager_->CreateDataChannel(
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001543 this, content->name, !sctp, data_channel_type_));
wu@webrtc.org91053e72013-08-10 07:18:04 +00001544 if (!data_channel_.get()) {
1545 return false;
1546 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001547 if (sctp) {
1548 mediastream_signaling_->OnDataTransportCreatedForSctp();
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001549 data_channel_->SignalDataReceived.connect(
1550 this, &WebRtcSession::OnDataChannelMessageReceived);
buildbot@webrtc.org1d66be22014-05-29 22:54:24 +00001551 data_channel_->SignalStreamClosedRemotely.connect(
1552 mediastream_signaling_,
1553 &MediaStreamSignaling::OnRemoteSctpDataChannelClosed);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001554 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001555 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001556}
1557
1558void WebRtcSession::CopySavedCandidates(
1559 SessionDescriptionInterface* dest_desc) {
1560 if (!dest_desc) {
1561 ASSERT(false);
1562 return;
1563 }
1564 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1565 dest_desc->AddCandidate(saved_candidates_[i]);
1566 delete saved_candidates_[i];
1567 }
1568 saved_candidates_.clear();
1569}
1570
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001571void WebRtcSession::OnDataChannelMessageReceived(
1572 cricket::DataChannel* channel,
1573 const cricket::ReceiveDataParams& params,
1574 const talk_base::Buffer& payload) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001575 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001576 if (params.type == cricket::DMT_CONTROL &&
1577 mediastream_signaling_->IsSctpSidAvailable(params.ssrc)) {
1578 // Received CONTROL on unused sid, process as an OPEN message.
1579 mediastream_signaling_->AddDataChannelFromOpenMessage(params, payload);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001580 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001581 // otherwise ignore the message.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001582}
1583
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001584// Returns false if bundle is enabled and rtcp_mux is disabled.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001585bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001586 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1587 if (!bundle_enabled)
1588 return true;
1589
1590 const cricket::ContentGroup* bundle_group =
1591 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1592 ASSERT(bundle_group != NULL);
1593
1594 const cricket::ContentInfos& contents = desc->contents();
1595 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1596 citer != contents.end(); ++citer) {
1597 const cricket::ContentInfo* content = (&*citer);
1598 ASSERT(content != NULL);
1599 if (bundle_group->HasContentName(content->name) &&
1600 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1601 if (!HasRtcpMuxEnabled(content))
1602 return false;
1603 }
1604 }
1605 // RTCP-MUX is enabled in all the contents.
1606 return true;
1607}
1608
1609bool WebRtcSession::HasRtcpMuxEnabled(
1610 const cricket::ContentInfo* content) {
1611 const cricket::MediaContentDescription* description =
1612 static_cast<cricket::MediaContentDescription*>(content->description);
1613 return description->rtcp_mux();
1614}
1615
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001616bool WebRtcSession::ValidateSessionDescription(
1617 const SessionDescriptionInterface* sdesc,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001618 cricket::ContentSource source, std::string* err_desc) {
1619 std::string type;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001620 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001621 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001622 }
1623
1624 if (!sdesc || !sdesc->description()) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001625 return BadSdp(source, type, kInvalidSdp, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001626 }
1627
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001628 type = sdesc->type();
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001629 Action action = GetAction(sdesc->type());
1630 if (source == cricket::CS_LOCAL) {
1631 if (!ExpectSetLocalDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001632 return BadLocalSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001633 } else {
1634 if (!ExpectSetRemoteDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001635 return BadRemoteSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001636 }
1637
1638 // Verify crypto settings.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001639 std::string crypto_error;
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +00001640 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
1641 dtls_enabled_) &&
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001642 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001643 return BadSdp(source, type, crypto_error, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001644 }
1645
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001646 // Verify ice-ufrag and ice-pwd.
1647 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001648 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001649 }
1650
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001651 if (!ValidateBundleSettings(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001652 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001653 }
1654
1655 // Verify m-lines in Answer when compared against Offer.
1656 if (action == kAnswer) {
1657 const cricket::SessionDescription* offer_desc =
1658 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1659 local_description()->description();
1660 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001661 return BadAnswerSdp(source, kMlineMismatch, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001662 }
1663 }
1664
1665 return true;
1666}
1667
1668bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1669 return ((action == kOffer && state() == STATE_INIT) ||
1670 // update local offer
1671 (action == kOffer && state() == STATE_SENTINITIATE) ||
1672 // update the current ongoing session.
1673 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1674 (action == kOffer && state() == STATE_SENTACCEPT) ||
1675 (action == kOffer && state() == STATE_INPROGRESS) ||
1676 // accept remote offer
1677 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1678 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1679 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1680 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1681}
1682
1683bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1684 return ((action == kOffer && state() == STATE_INIT) ||
1685 // update remote offer
1686 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1687 // update the current ongoing session
1688 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1689 (action == kOffer && state() == STATE_SENTACCEPT) ||
1690 (action == kOffer && state() == STATE_INPROGRESS) ||
1691 // accept local offer
1692 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1693 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1694 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1695 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1696}
1697
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001698std::string WebRtcSession::GetSessionErrorMsg() {
1699 std::ostringstream desc;
1700 desc << kSessionError << GetErrorCodeString(error()) << ". ";
1701 desc << kSessionErrorDesc << error_desc() << ".";
1702 return desc.str();
1703}
1704
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001705} // namespace webrtc