blob: 04cbe029f8eb0f4fda3e51033bf07e921e657164 [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
30#include <algorithm>
31#include <climits>
32#include <vector>
33
34#include "talk/app/webrtc/jsepicecandidate.h"
35#include "talk/app/webrtc/jsepsessiondescription.h"
36#include "talk/app/webrtc/mediaconstraintsinterface.h"
37#include "talk/app/webrtc/mediastreamsignaling.h"
38#include "talk/app/webrtc/peerconnectioninterface.h"
wu@webrtc.org91053e72013-08-10 07:18:04 +000039#include "talk/app/webrtc/webrtcsessiondescriptionfactory.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000040#include "talk/base/helpers.h"
41#include "talk/base/logging.h"
42#include "talk/base/stringencode.h"
43#include "talk/media/base/constants.h"
44#include "talk/media/base/videocapturer.h"
45#include "talk/session/media/channel.h"
46#include "talk/session/media/channelmanager.h"
47#include "talk/session/media/mediasession.h"
48
49using cricket::ContentInfo;
50using cricket::ContentInfos;
51using cricket::MediaContentDescription;
52using cricket::SessionDescription;
53using cricket::TransportInfo;
54
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055namespace webrtc {
56
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000057const char MediaConstraintsInterface::kInternalConstraintPrefix[] = "internal";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058
59// Supported MediaConstraints.
60// DTLS-SRTP pseudo-constraints.
61const char MediaConstraintsInterface::kEnableDtlsSrtp[] =
62 "DtlsSrtpKeyAgreement";
63// DataChannel pseudo constraints.
64const char MediaConstraintsInterface::kEnableRtpDataChannels[] =
65 "RtpDataChannels";
66// This constraint is for internal use only, representing the Chrome command
67// line flag. So it is prefixed with kInternalConstraintPrefix so JS values
68// will be removed.
69const char MediaConstraintsInterface::kEnableSctpDataChannels[] =
70 "internalSctpDataChannels";
71
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +000072const char MediaConstraintsInterface::kInternalDisableEncryption[] =
73 "internalDisableEncryption";
74
henrike@webrtc.org28e20752013-07-10 00:45:36 +000075// Error messages
76const char kSetLocalSdpFailed[] = "SetLocalDescription failed: ";
77const char kSetRemoteSdpFailed[] = "SetRemoteDescription failed: ";
78const char kCreateChannelFailed[] = "Failed to create channels.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000079const char kBundleWithoutRtcpMux[] = "RTCP-MUX must be enabled when BUNDLE "
80 "is enabled.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000081const char kInvalidCandidates[] = "Description contains invalid candidates.";
82const char kInvalidSdp[] = "Invalid session description.";
83const char kMlineMismatch[] =
84 "Offer and answer descriptions m-lines are not matching. "
85 "Rejecting answer.";
86const char kSdpWithoutCrypto[] = "Called with a SDP without crypto enabled.";
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000087const char kSdpWithoutSdesAndDtlsDisabled[] =
88 "Called with a SDP without SDES crypto and DTLS disabled locally.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089const char kSessionError[] = "Session error code: ";
90const char kUpdateStateFailed[] = "Failed to update session state: ";
91const char kPushDownOfferTDFailed[] =
92 "Failed to push down offer transport description.";
93const char kPushDownPranswerTDFailed[] =
94 "Failed to push down pranswer transport description.";
95const char kPushDownAnswerTDFailed[] =
96 "Failed to push down answer transport description.";
97
98// Compares |answer| against |offer|. Comparision is done
99// for number of m-lines in answer against offer. If matches true will be
100// returned otherwise false.
101static bool VerifyMediaDescriptions(
102 const SessionDescription* answer, const SessionDescription* offer) {
103 if (offer->contents().size() != answer->contents().size())
104 return false;
105
106 for (size_t i = 0; i < offer->contents().size(); ++i) {
107 if ((offer->contents()[i].name) != answer->contents()[i].name) {
108 return false;
109 }
110 }
111 return true;
112}
113
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000114// Checks that each non-rejected content has SDES crypto keys or a DTLS
115// fingerprint. Mismatches, such as replying with a DTLS fingerprint to SDES
116// keys, will be caught in Transport negotiation, and backstopped by Channel's
117// |secure_required| check.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000118static bool VerifyCrypto(const SessionDescription* desc,
119 bool dtls_enabled,
120 std::string* error) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000121 const ContentInfos& contents = desc->contents();
122 for (size_t index = 0; index < contents.size(); ++index) {
123 const ContentInfo* cinfo = &contents[index];
124 if (cinfo->rejected) {
125 continue;
126 }
127
128 // If the content isn't rejected, crypto must be present.
129 const MediaContentDescription* media =
130 static_cast<const MediaContentDescription*>(cinfo->description);
131 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
132 if (!media || !tinfo) {
133 // Something is not right.
134 LOG(LS_ERROR) << kInvalidSdp;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000135 *error = kInvalidSdp;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136 return false;
137 }
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000138 if (media->cryptos().empty()) {
139 if (!tinfo->description.identity_fingerprint) {
140 // Crypto must be supplied.
141 LOG(LS_WARNING) << "Session description must have SDES or DTLS-SRTP.";
142 *error = kSdpWithoutCrypto;
143 return false;
144 }
145 if (!dtls_enabled) {
146 LOG(LS_WARNING) <<
147 "Session description must have SDES when DTLS disabled.";
148 *error = kSdpWithoutSdesAndDtlsDisabled;
149 return false;
150 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000151 }
152 }
153
154 return true;
155}
156
wu@webrtc.org91053e72013-08-10 07:18:04 +0000157// Forces |sdesc->crypto_required| to the appropriate state based on the
158// current security policy, to ensure a failure occurs if there is an error
159// in crypto negotiation.
160// Called when processing the local session description.
161static void UpdateSessionDescriptionSecurePolicy(
162 cricket::SecureMediaPolicy secure_policy,
163 SessionDescription* sdesc) {
164 if (!sdesc) {
165 return;
166 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000167
wu@webrtc.org91053e72013-08-10 07:18:04 +0000168 // Updating the |crypto_required_| in MediaContentDescription to the
169 // appropriate state based on the current security policy.
170 for (cricket::ContentInfos::iterator iter = sdesc->contents().begin();
171 iter != sdesc->contents().end(); ++iter) {
172 if (cricket::IsMediaContent(&*iter)) {
173 MediaContentDescription* mdesc =
174 static_cast<MediaContentDescription*> (iter->description);
175 if (mdesc) {
176 mdesc->set_crypto_required(secure_policy == cricket::SEC_REQUIRED);
177 }
178 }
179 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000180}
181
182static bool GetAudioSsrcByTrackId(
183 const SessionDescription* session_description,
184 const std::string& track_id, uint32 *ssrc) {
185 const cricket::ContentInfo* audio_info =
186 cricket::GetFirstAudioContent(session_description);
187 if (!audio_info) {
188 LOG(LS_ERROR) << "Audio not used in this call";
189 return false;
190 }
191
192 const cricket::MediaContentDescription* audio_content =
193 static_cast<const cricket::MediaContentDescription*>(
194 audio_info->description);
195 cricket::StreamParams stream;
196 if (!cricket::GetStreamByIds(audio_content->streams(), "", track_id,
197 &stream)) {
198 return false;
199 }
200 *ssrc = stream.first_ssrc();
201 return true;
202}
203
204static bool GetTrackIdBySsrc(const SessionDescription* session_description,
205 uint32 ssrc, std::string* track_id) {
206 ASSERT(track_id != NULL);
207
208 cricket::StreamParams stream_out;
209 const cricket::ContentInfo* audio_info =
210 cricket::GetFirstAudioContent(session_description);
211 if (!audio_info) {
212 return false;
213 }
214 const cricket::MediaContentDescription* audio_content =
215 static_cast<const cricket::MediaContentDescription*>(
216 audio_info->description);
217
218 if (cricket::GetStreamBySsrc(audio_content->streams(), ssrc, &stream_out)) {
219 *track_id = stream_out.id;
220 return true;
221 }
222
223 const cricket::ContentInfo* video_info =
224 cricket::GetFirstVideoContent(session_description);
225 if (!video_info) {
226 return false;
227 }
228 const cricket::MediaContentDescription* video_content =
229 static_cast<const cricket::MediaContentDescription*>(
230 video_info->description);
231
232 if (cricket::GetStreamBySsrc(video_content->streams(), ssrc, &stream_out)) {
233 *track_id = stream_out.id;
234 return true;
235 }
236 return false;
237}
238
239static bool BadSdp(const std::string& desc, std::string* err_desc) {
240 if (err_desc) {
241 *err_desc = desc;
242 }
243 LOG(LS_ERROR) << desc;
244 return false;
245}
246
247static bool BadLocalSdp(const std::string& desc, std::string* err_desc) {
248 std::string set_local_sdp_failed = kSetLocalSdpFailed;
249 set_local_sdp_failed.append(desc);
250 return BadSdp(set_local_sdp_failed, err_desc);
251}
252
253static bool BadRemoteSdp(const std::string& desc, std::string* err_desc) {
254 std::string set_remote_sdp_failed = kSetRemoteSdpFailed;
255 set_remote_sdp_failed.append(desc);
256 return BadSdp(set_remote_sdp_failed, err_desc);
257}
258
259static bool BadSdp(cricket::ContentSource source,
260 const std::string& desc, std::string* err_desc) {
261 if (source == cricket::CS_LOCAL) {
262 return BadLocalSdp(desc, err_desc);
263 } else {
264 return BadRemoteSdp(desc, err_desc);
265 }
266}
267
268static std::string SessionErrorMsg(cricket::BaseSession::Error error) {
269 std::ostringstream desc;
270 desc << kSessionError << error;
271 return desc.str();
272}
273
274#define GET_STRING_OF_STATE(state) \
275 case cricket::BaseSession::state: \
276 result = #state; \
277 break;
278
279static std::string GetStateString(cricket::BaseSession::State state) {
280 std::string result;
281 switch (state) {
282 GET_STRING_OF_STATE(STATE_INIT)
283 GET_STRING_OF_STATE(STATE_SENTINITIATE)
284 GET_STRING_OF_STATE(STATE_RECEIVEDINITIATE)
285 GET_STRING_OF_STATE(STATE_SENTPRACCEPT)
286 GET_STRING_OF_STATE(STATE_SENTACCEPT)
287 GET_STRING_OF_STATE(STATE_RECEIVEDPRACCEPT)
288 GET_STRING_OF_STATE(STATE_RECEIVEDACCEPT)
289 GET_STRING_OF_STATE(STATE_SENTMODIFY)
290 GET_STRING_OF_STATE(STATE_RECEIVEDMODIFY)
291 GET_STRING_OF_STATE(STATE_SENTREJECT)
292 GET_STRING_OF_STATE(STATE_RECEIVEDREJECT)
293 GET_STRING_OF_STATE(STATE_SENTREDIRECT)
294 GET_STRING_OF_STATE(STATE_SENTTERMINATE)
295 GET_STRING_OF_STATE(STATE_RECEIVEDTERMINATE)
296 GET_STRING_OF_STATE(STATE_INPROGRESS)
297 GET_STRING_OF_STATE(STATE_DEINIT)
298 default:
299 ASSERT(false);
300 break;
301 }
302 return result;
303}
304
305#define GET_STRING_OF_ERROR(err) \
306 case cricket::BaseSession::err: \
307 result = #err; \
308 break;
309
310static std::string GetErrorString(cricket::BaseSession::Error err) {
311 std::string result;
312 switch (err) {
313 GET_STRING_OF_ERROR(ERROR_NONE)
314 GET_STRING_OF_ERROR(ERROR_TIME)
315 GET_STRING_OF_ERROR(ERROR_RESPONSE)
316 GET_STRING_OF_ERROR(ERROR_NETWORK)
317 GET_STRING_OF_ERROR(ERROR_CONTENT)
318 GET_STRING_OF_ERROR(ERROR_TRANSPORT)
319 default:
320 ASSERT(false);
321 break;
322 }
323 return result;
324}
325
326static bool SetSessionStateFailed(cricket::ContentSource source,
327 cricket::BaseSession::Error err,
328 std::string* err_desc) {
329 std::string set_state_err = kUpdateStateFailed;
330 set_state_err.append(GetErrorString(err));
331 return BadSdp(source, set_state_err, err_desc);
332}
333
334// Help class used to remember if a a remote peer has requested ice restart by
335// by sending a description with new ice ufrag and password.
336class IceRestartAnswerLatch {
337 public:
338 IceRestartAnswerLatch() : ice_restart_(false) { }
339
wu@webrtc.org91053e72013-08-10 07:18:04 +0000340 // Returns true if CheckForRemoteIceRestart has been called with a new session
341 // description where ice password and ufrag has changed since last time
342 // Reset() was called.
343 bool Get() const {
344 return ice_restart_;
345 }
346
347 void Reset() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000348 if (ice_restart_) {
349 ice_restart_ = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000350 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000351 }
352
353 void CheckForRemoteIceRestart(
354 const SessionDescriptionInterface* old_desc,
355 const SessionDescriptionInterface* new_desc) {
356 if (!old_desc || new_desc->type() != SessionDescriptionInterface::kOffer) {
357 return;
358 }
359 const SessionDescription* new_sd = new_desc->description();
360 const SessionDescription* old_sd = old_desc->description();
361 const ContentInfos& contents = new_sd->contents();
362 for (size_t index = 0; index < contents.size(); ++index) {
363 const ContentInfo* cinfo = &contents[index];
364 if (cinfo->rejected) {
365 continue;
366 }
367 // If the content isn't rejected, check if ufrag and password has
368 // changed.
369 const cricket::TransportDescription* new_transport_desc =
370 new_sd->GetTransportDescriptionByName(cinfo->name);
371 const cricket::TransportDescription* old_transport_desc =
372 old_sd->GetTransportDescriptionByName(cinfo->name);
373 if (!new_transport_desc || !old_transport_desc) {
374 // No transport description exist. This is not an ice restart.
375 continue;
376 }
377 if (new_transport_desc->ice_pwd != old_transport_desc->ice_pwd &&
378 new_transport_desc->ice_ufrag != old_transport_desc->ice_ufrag) {
379 LOG(LS_INFO) << "Remote peer request ice restart.";
380 ice_restart_ = true;
381 break;
382 }
383 }
384 }
385
386 private:
387 bool ice_restart_;
388};
389
wu@webrtc.org91053e72013-08-10 07:18:04 +0000390WebRtcSession::WebRtcSession(
391 cricket::ChannelManager* channel_manager,
392 talk_base::Thread* signaling_thread,
393 talk_base::Thread* worker_thread,
394 cricket::PortAllocator* port_allocator,
395 MediaStreamSignaling* mediastream_signaling)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000396 : cricket::BaseSession(signaling_thread, worker_thread, port_allocator,
397 talk_base::ToString(talk_base::CreateRandomId64() &
398 LLONG_MAX),
399 cricket::NS_JINGLE_RTP, false),
400 // RFC 3264: The numeric value of the session id and version in the
401 // o line MUST be representable with a "64 bit signed integer".
402 // Due to this constraint session id |sid_| is max limited to LLONG_MAX.
403 channel_manager_(channel_manager),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000404 mediastream_signaling_(mediastream_signaling),
405 ice_observer_(NULL),
406 ice_connection_state_(PeerConnectionInterface::kIceConnectionNew),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000407 older_version_remote_peer_(false),
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000408 dtls_enabled_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000409 data_channel_type_(cricket::DCT_NONE),
410 ice_restart_latch_(new IceRestartAnswerLatch) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000411}
412
413WebRtcSession::~WebRtcSession() {
414 if (voice_channel_.get()) {
415 SignalVoiceChannelDestroyed();
416 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
417 }
418 if (video_channel_.get()) {
419 SignalVideoChannelDestroyed();
420 channel_manager_->DestroyVideoChannel(video_channel_.release());
421 }
422 if (data_channel_.get()) {
423 SignalDataChannelDestroyed();
424 channel_manager_->DestroyDataChannel(data_channel_.release());
425 }
426 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
427 delete saved_candidates_[i];
428 }
429 delete identity();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000430}
431
wu@webrtc.org91053e72013-08-10 07:18:04 +0000432bool WebRtcSession::Initialize(
433 const MediaConstraintsInterface* constraints,
434 DTLSIdentityServiceInterface* dtls_identity_service) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000435 // TODO(perkj): Take |constraints| into consideration. Return false if not all
436 // mandatory constraints can be fulfilled. Note that |constraints|
437 // can be null.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000438 bool value;
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000439
440 // Enable DTLS by default if |dtls_identity_service| is valid.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000441 dtls_enabled_ = (dtls_identity_service != NULL);
442 // |constraints| can override the default |dtls_enabled_| value.
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000443 if (FindConstraint(
444 constraints,
445 MediaConstraintsInterface::kEnableDtlsSrtp,
446 &value, NULL)) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000447 dtls_enabled_ = value;
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000448 }
449
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000450 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
451 // It takes precendence over the kEnableSctpDataChannels constraint.
452 if (FindConstraint(
453 constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
454 &value, NULL) && value) {
455 LOG(LS_INFO) << "Allowing RTP data engine.";
456 data_channel_type_ = cricket::DCT_RTP;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000457 } else {
458 bool sctp_enabled = FindConstraint(
459 constraints,
460 MediaConstraintsInterface::kEnableSctpDataChannels,
461 &value, NULL) && value;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000462 // DTLS has to be enabled to use SCTP.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000463 if (sctp_enabled && dtls_enabled_) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000464 LOG(LS_INFO) << "Allowing SCTP data engine.";
465 data_channel_type_ = cricket::DCT_SCTP;
466 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000467 }
468 if (data_channel_type_ != cricket::DCT_NONE) {
469 mediastream_signaling_->SetDataChannelFactory(this);
470 }
471
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000472 const cricket::VideoCodec default_codec(
473 JsepSessionDescription::kDefaultVideoCodecId,
474 JsepSessionDescription::kDefaultVideoCodecName,
475 JsepSessionDescription::kMaxVideoCodecWidth,
476 JsepSessionDescription::kMaxVideoCodecHeight,
477 JsepSessionDescription::kDefaultVideoCodecFramerate,
478 JsepSessionDescription::kDefaultVideoCodecPreference);
479 channel_manager_->SetDefaultVideoEncoderConfig(
480 cricket::VideoEncoderConfig(default_codec));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000481
482 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
483 signaling_thread(),
484 channel_manager_,
485 mediastream_signaling_,
486 dtls_identity_service,
487 this,
488 id(),
489 data_channel_type_,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000490 dtls_enabled_));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000491
492 webrtc_session_desc_factory_->SignalIdentityReady.connect(
493 this, &WebRtcSession::OnIdentityReady);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000494
495 // Disable encryption if kDisableEncryption is set.
496 if (FindConstraint(
497 constraints,
498 MediaConstraintsInterface::kInternalDisableEncryption,
499 &value, NULL) && value) {
500 webrtc_session_desc_factory_->set_secure(cricket::SEC_DISABLED);
501 }
502
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000503 return true;
504}
505
506void WebRtcSession::Terminate() {
507 SetState(STATE_RECEIVEDTERMINATE);
508 RemoveUnusedChannelsAndTransports(NULL);
509 ASSERT(voice_channel_.get() == NULL);
510 ASSERT(video_channel_.get() == NULL);
511 ASSERT(data_channel_.get() == NULL);
512}
513
514bool WebRtcSession::StartCandidatesAllocation() {
515 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
516 // from TransportProxy to start gathering ice candidates.
517 SpeculativelyConnectAllTransportChannels();
518 if (!saved_candidates_.empty()) {
519 // If there are saved candidates which arrived before local description is
520 // set, copy those to remote description.
521 CopySavedCandidates(remote_desc_.get());
522 }
523 // Push remote candidates present in remote description to transport channels.
524 UseCandidatesInSessionDescription(remote_desc_.get());
525 return true;
526}
527
528void WebRtcSession::set_secure_policy(
529 cricket::SecureMediaPolicy secure_policy) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000530 webrtc_session_desc_factory_->set_secure(secure_policy);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000531}
532
wu@webrtc.org91053e72013-08-10 07:18:04 +0000533cricket::SecureMediaPolicy WebRtcSession::secure_policy() const {
534 return webrtc_session_desc_factory_->secure();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000535}
536
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000537bool WebRtcSession::GetSslRole(talk_base::SSLRole* role) {
538 if (local_description() == NULL || remote_description() == NULL) {
539 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
540 << "SSL Role of the session.";
541 return false;
542 }
543
544 // TODO(mallinath) - Return role of each transport, as role may differ from
545 // one another.
546 // In current implementaion we just return the role of first transport in the
547 // transport map.
548 for (cricket::TransportMap::const_iterator iter = transport_proxies().begin();
549 iter != transport_proxies().end(); ++iter) {
550 if (iter->second->impl()) {
551 return iter->second->impl()->GetSslRole(role);
552 }
553 }
554 return false;
555}
556
wu@webrtc.org91053e72013-08-10 07:18:04 +0000557void WebRtcSession::CreateOffer(CreateSessionDescriptionObserver* observer,
558 const MediaConstraintsInterface* constraints) {
559 webrtc_session_desc_factory_->CreateOffer(observer, constraints);
560}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000561
wu@webrtc.org91053e72013-08-10 07:18:04 +0000562void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
563 const MediaConstraintsInterface* constraints) {
564 webrtc_session_desc_factory_->CreateAnswer(observer, constraints);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000565}
566
567bool WebRtcSession::SetLocalDescription(SessionDescriptionInterface* desc,
568 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000569 // Takes the ownership of |desc| regardless of the result.
570 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
571
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000572 // Validate SDP.
573 if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
574 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000575 }
576
577 // Update the initiator flag if this session is the initiator.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000578 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000579 if (state() == STATE_INIT && action == kOffer) {
580 set_initiator(true);
581 }
582
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000583 cricket::SecureMediaPolicy secure_policy =
584 webrtc_session_desc_factory_->secure();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000585 // Update the MediaContentDescription crypto settings as per the policy set.
wu@webrtc.org91053e72013-08-10 07:18:04 +0000586 UpdateSessionDescriptionSecurePolicy(secure_policy, desc->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000587
588 set_local_description(desc->description()->Copy());
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000589 local_desc_.reset(desc_temp.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000590
591 // Transport and Media channels will be created only when offer is set.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000592 if (action == kOffer && !CreateChannels(local_desc_->description())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000593 // TODO(mallinath) - Handle CreateChannel failure, as new local description
594 // is applied. Restore back to old description.
595 return BadLocalSdp(kCreateChannelFailed, err_desc);
596 }
597
598 // Remove channel and transport proxies, if MediaContentDescription is
599 // rejected.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000600 RemoveUnusedChannelsAndTransports(local_desc_->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000601
602 if (!UpdateSessionState(action, cricket::CS_LOCAL,
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000603 local_desc_->description(), err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000604 return false;
605 }
606 // Kick starting the ice candidates allocation.
607 StartCandidatesAllocation();
608
609 // Update state and SSRC of local MediaStreams and DataChannels based on the
610 // local session description.
611 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
612
613 if (error() != cricket::BaseSession::ERROR_NONE) {
614 return BadLocalSdp(SessionErrorMsg(error()), err_desc);
615 }
616 return true;
617}
618
619bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
620 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000621 // Takes the ownership of |desc| regardless of the result.
622 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
623
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000624 // Validate SDP.
625 if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
626 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000627 }
628
629 // Transport and Media channels will be created only when offer is set.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000630 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000631 if (action == kOffer && !CreateChannels(desc->description())) {
632 // TODO(mallinath) - Handle CreateChannel failure, as new local description
633 // is applied. Restore back to old description.
634 return BadRemoteSdp(kCreateChannelFailed, err_desc);
635 }
636
637 // Remove channel and transport proxies, if MediaContentDescription is
638 // rejected.
639 RemoveUnusedChannelsAndTransports(desc->description());
640
641 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
642 // is called.
643 set_remote_description(desc->description()->Copy());
644 if (!UpdateSessionState(action, cricket::CS_REMOTE,
645 desc->description(), err_desc)) {
646 return false;
647 }
648
649 // Update remote MediaStreams.
650 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
651 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000652 return BadRemoteSdp(kInvalidCandidates, err_desc);
653 }
654
655 // Copy all saved candidates.
656 CopySavedCandidates(desc);
657 // We retain all received candidates.
wu@webrtc.org91053e72013-08-10 07:18:04 +0000658 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
659 remote_desc_.get(), desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000660 // Check if this new SessionDescription contains new ice ufrag and password
661 // that indicates the remote peer requests ice restart.
662 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(),
663 desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000664 remote_desc_.reset(desc_temp.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000665 if (error() != cricket::BaseSession::ERROR_NONE) {
666 return BadRemoteSdp(SessionErrorMsg(error()), err_desc);
667 }
668 return true;
669}
670
671bool WebRtcSession::UpdateSessionState(
672 Action action, cricket::ContentSource source,
673 const cricket::SessionDescription* desc,
674 std::string* err_desc) {
675 // If there's already a pending error then no state transition should happen.
676 // But all call-sites should be verifying this before calling us!
677 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
678 if (action == kOffer) {
679 if (!PushdownTransportDescription(source, cricket::CA_OFFER)) {
680 return BadSdp(source, kPushDownOfferTDFailed, err_desc);
681 }
682 SetState(source == cricket::CS_LOCAL ?
683 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
684 if (error() != cricket::BaseSession::ERROR_NONE) {
685 return SetSessionStateFailed(source, error(), err_desc);
686 }
687 } else if (action == kPrAnswer) {
688 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER)) {
689 return BadSdp(source, kPushDownPranswerTDFailed, err_desc);
690 }
691 EnableChannels();
692 SetState(source == cricket::CS_LOCAL ?
693 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
694 if (error() != cricket::BaseSession::ERROR_NONE) {
695 return SetSessionStateFailed(source, error(), err_desc);
696 }
697 } else if (action == kAnswer) {
698 if (!PushdownTransportDescription(source, cricket::CA_ANSWER)) {
699 return BadSdp(source, kPushDownAnswerTDFailed, err_desc);
700 }
701 MaybeEnableMuxingSupport();
702 EnableChannels();
703 SetState(source == cricket::CS_LOCAL ?
704 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
705 if (error() != cricket::BaseSession::ERROR_NONE) {
706 return SetSessionStateFailed(source, error(), err_desc);
707 }
708 }
709 return true;
710}
711
712WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
713 if (type == SessionDescriptionInterface::kOffer) {
714 return WebRtcSession::kOffer;
715 } else if (type == SessionDescriptionInterface::kPrAnswer) {
716 return WebRtcSession::kPrAnswer;
717 } else if (type == SessionDescriptionInterface::kAnswer) {
718 return WebRtcSession::kAnswer;
719 }
720 ASSERT(false && "unknown action type");
721 return WebRtcSession::kOffer;
722}
723
724bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
725 if (state() == STATE_INIT) {
726 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
727 << "without any offer (local or remote) "
728 << "session description.";
729 return false;
730 }
731
732 if (!candidate) {
733 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
734 return false;
735 }
736
737 if (!local_description() || !remote_description()) {
738 LOG(LS_INFO) << "ProcessIceMessage: Remote description not set, "
739 << "save the candidate for later use.";
740 saved_candidates_.push_back(
741 new JsepIceCandidate(candidate->sdp_mid(), candidate->sdp_mline_index(),
742 candidate->candidate()));
743 return true;
744 }
745
746 // Add this candidate to the remote session description.
747 if (!remote_desc_->AddCandidate(candidate)) {
748 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
749 return false;
750 }
751
752 return UseCandidatesInSessionDescription(remote_desc_.get());
753}
754
755bool WebRtcSession::GetTrackIdBySsrc(uint32 ssrc, std::string* id) {
756 if (GetLocalTrackId(ssrc, id)) {
757 if (GetRemoteTrackId(ssrc, id)) {
758 LOG(LS_WARNING) << "SSRC " << ssrc
759 << " exists in both local and remote descriptions";
760 return true; // We return the remote track id.
761 }
762 return true;
763 } else {
764 return GetRemoteTrackId(ssrc, id);
765 }
766}
767
768bool WebRtcSession::GetLocalTrackId(uint32 ssrc, std::string* track_id) {
769 if (!BaseSession::local_description())
770 return false;
771 return webrtc::GetTrackIdBySsrc(
772 BaseSession::local_description(), ssrc, track_id);
773}
774
775bool WebRtcSession::GetRemoteTrackId(uint32 ssrc, std::string* track_id) {
776 if (!BaseSession::remote_description())
777 return false;
778 return webrtc::GetTrackIdBySsrc(
779 BaseSession::remote_description(), ssrc, track_id);
780}
781
782std::string WebRtcSession::BadStateErrMsg(
783 const std::string& type, State state) {
784 std::ostringstream desc;
785 desc << "Called with type in wrong state, "
786 << "type: " << type << " state: " << GetStateString(state);
787 return desc.str();
788}
789
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000790void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable,
791 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000792 ASSERT(signaling_thread()->IsCurrent());
793 if (!voice_channel_) {
794 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
795 return;
796 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000797 if (!voice_channel_->SetRemoteRenderer(ssrc, renderer)) {
798 // SetRenderer() can fail if the ssrc does not match any playout channel.
799 LOG(LS_ERROR) << "SetAudioPlayout: ssrc is incorrect: " << ssrc;
800 return;
801 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000802 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
803 // Allow that SetOutputScaling fail if |enable| is false but assert
804 // otherwise. This in the normal case when the underlying media channel has
805 // already been deleted.
806 ASSERT(enable == false);
807 }
808}
809
810void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000811 const cricket::AudioOptions& options,
812 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000813 ASSERT(signaling_thread()->IsCurrent());
814 if (!voice_channel_) {
815 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
816 return;
817 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000818 if (!voice_channel_->SetLocalRenderer(ssrc, renderer)) {
819 // SetRenderer() can fail if the ssrc does not match any send channel.
820 LOG(LS_ERROR) << "SetAudioSend: ssrc is incorrect: " << ssrc;
821 return;
822 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000823 if (!voice_channel_->MuteStream(ssrc, !enable)) {
824 // Allow that MuteStream fail if |enable| is false but assert otherwise.
825 // This in the normal case when the underlying media channel has already
826 // been deleted.
827 ASSERT(enable == false);
828 return;
829 }
830 if (enable)
831 voice_channel_->SetChannelOptions(options);
832}
833
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000834bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
835 cricket::VideoCapturer* camera) {
836 ASSERT(signaling_thread()->IsCurrent());
837
838 if (!video_channel_.get()) {
839 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
840 // support video.
841 LOG(LS_WARNING) << "Video not used in this call.";
842 return false;
843 }
844 if (!video_channel_->SetCapturer(ssrc, camera)) {
845 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
846 // This in the normal case when the underlying media channel has already
847 // been deleted.
848 ASSERT(camera == NULL);
849 return false;
850 }
851 return true;
852}
853
854void WebRtcSession::SetVideoPlayout(uint32 ssrc,
855 bool enable,
856 cricket::VideoRenderer* renderer) {
857 ASSERT(signaling_thread()->IsCurrent());
858 if (!video_channel_) {
859 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
860 return;
861 }
862 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
863 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
864 // This in the normal case when the underlying media channel has already
865 // been deleted.
866 ASSERT(renderer == NULL);
867 }
868}
869
870void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
871 const cricket::VideoOptions* options) {
872 ASSERT(signaling_thread()->IsCurrent());
873 if (!video_channel_) {
874 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
875 return;
876 }
877 if (!video_channel_->MuteStream(ssrc, !enable)) {
878 // Allow that MuteStream fail if |enable| is false but assert otherwise.
879 // This in the normal case when the underlying media channel has already
880 // been deleted.
881 ASSERT(enable == false);
882 return;
883 }
884 if (enable && options)
885 video_channel_->SetChannelOptions(*options);
886}
887
888bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
889 ASSERT(signaling_thread()->IsCurrent());
890 if (!voice_channel_) {
891 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
892 return false;
893 }
894 uint32 send_ssrc = 0;
895 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
896 // exists.
897 if (!GetAudioSsrcByTrackId(BaseSession::local_description(), track_id,
898 &send_ssrc)) {
899 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
900 return false;
901 }
902 return voice_channel_->CanInsertDtmf();
903}
904
905bool WebRtcSession::InsertDtmf(const std::string& track_id,
906 int code, int duration) {
907 ASSERT(signaling_thread()->IsCurrent());
908 if (!voice_channel_) {
909 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
910 return false;
911 }
912 uint32 send_ssrc = 0;
913 if (!VERIFY(GetAudioSsrcByTrackId(BaseSession::local_description(),
914 track_id, &send_ssrc))) {
915 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
916 return false;
917 }
918 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
919 cricket::DF_SEND)) {
920 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
921 return false;
922 }
923 return true;
924}
925
926sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
927 return &SignalVoiceChannelDestroyed;
928}
929
wu@webrtc.org78187522013-10-07 23:32:02 +0000930bool WebRtcSession::SendData(const cricket::SendDataParams& params,
931 const talk_base::Buffer& payload,
932 cricket::SendDataResult* result) {
933 if (!data_channel_.get()) {
934 LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
935 return false;
936 }
937 return data_channel_->SendData(params, payload, result);
938}
939
940bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
941 if (!data_channel_.get()) {
942 LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
943 return false;
944 }
945
946 data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
947 &DataChannel::OnChannelReady);
948 data_channel_->SignalDataReceived.connect(webrtc_data_channel,
949 &DataChannel::OnDataReceived);
950 cricket::StreamParams params =
951 cricket::StreamParams::CreateLegacy(webrtc_data_channel->id());
952 data_channel_->AddRecvStream(params);
953 data_channel_->AddSendStream(params);
954 return true;
955}
956
957void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
958 data_channel_->RemoveSendStream(webrtc_data_channel->id());
959 data_channel_->RemoveRecvStream(webrtc_data_channel->id());
960 data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
961 data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
962}
963
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000964talk_base::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
wu@webrtc.org78187522013-10-07 23:32:02 +0000965 const std::string& label,
966 const DataChannelInit* config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000967 if (state() == STATE_RECEIVEDTERMINATE) {
968 return NULL;
969 }
970 if (data_channel_type_ == cricket::DCT_NONE) {
971 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
972 return NULL;
973 }
974 DataChannelInit new_config = config ? (*config) : DataChannelInit();
975
976 if (data_channel_type_ == cricket::DCT_SCTP) {
977 if (new_config.id < 0) {
978 if (!mediastream_signaling_->AllocateSctpId(&new_config.id)) {
979 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
980 return NULL;
981 }
982 } else if (!mediastream_signaling_->IsSctpIdAvailable(new_config.id)) {
983 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
984 << "because the id is already in use or out of range.";
985 return NULL;
986 }
987 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000988
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989 talk_base::scoped_refptr<DataChannel> channel(
wu@webrtc.org78187522013-10-07 23:32:02 +0000990 DataChannel::Create(this, data_channel_type_, label, &new_config));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000991 if (channel == NULL)
992 return NULL;
993 if (!mediastream_signaling_->AddDataChannel(channel))
994 return NULL;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000995 if (data_channel_type_ == cricket::DCT_SCTP) {
996 if (config == NULL) {
997 LOG(LS_WARNING) << "Could not send data channel OPEN message"
998 << " because of NULL config.";
999 return NULL;
1000 }
1001 if (data_channel_.get()) {
1002 channel->SetReceiveSsrc(new_config.id);
1003 channel->SetSendSsrc(new_config.id);
wu@webrtc.org91053e72013-08-10 07:18:04 +00001004 }
1005 if (!config->negotiated) {
1006 talk_base::Buffer *payload = new talk_base::Buffer;
1007 if (!mediastream_signaling_->WriteDataChannelOpenMessage(
1008 label, *config, payload)) {
1009 LOG(LS_WARNING) << "Could not write data channel OPEN message";
1010 }
1011 // SendControl may queue the message until the data channel's set up,
1012 // or congestion clears.
1013 channel->SendControl(payload);
1014 }
1015 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001016 return channel;
1017}
1018
1019cricket::DataChannelType WebRtcSession::data_channel_type() const {
1020 return data_channel_type_;
1021}
1022
wu@webrtc.org91053e72013-08-10 07:18:04 +00001023bool WebRtcSession::IceRestartPending() const {
1024 return ice_restart_latch_->Get();
1025}
1026
1027void WebRtcSession::ResetIceRestartLatch() {
1028 ice_restart_latch_->Reset();
1029}
1030
1031void WebRtcSession::OnIdentityReady(talk_base::SSLIdentity* identity) {
1032 SetIdentity(identity);
1033}
1034
1035bool WebRtcSession::waiting_for_identity() const {
1036 return webrtc_session_desc_factory_->waiting_for_identity();
1037}
1038
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039void WebRtcSession::SetIceConnectionState(
1040 PeerConnectionInterface::IceConnectionState state) {
1041 if (ice_connection_state_ == state) {
1042 return;
1043 }
1044
1045 // ASSERT that the requested transition is allowed. Note that
1046 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1047 // within PeerConnection). This switch statement should compile away when
1048 // ASSERTs are disabled.
1049 switch (ice_connection_state_) {
1050 case PeerConnectionInterface::kIceConnectionNew:
1051 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1052 break;
1053 case PeerConnectionInterface::kIceConnectionChecking:
1054 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1055 state == PeerConnectionInterface::kIceConnectionConnected);
1056 break;
1057 case PeerConnectionInterface::kIceConnectionConnected:
1058 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1059 state == PeerConnectionInterface::kIceConnectionChecking ||
1060 state == PeerConnectionInterface::kIceConnectionCompleted);
1061 break;
1062 case PeerConnectionInterface::kIceConnectionCompleted:
1063 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1064 state == PeerConnectionInterface::kIceConnectionDisconnected);
1065 break;
1066 case PeerConnectionInterface::kIceConnectionFailed:
1067 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1068 break;
1069 case PeerConnectionInterface::kIceConnectionDisconnected:
1070 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1071 state == PeerConnectionInterface::kIceConnectionConnected ||
1072 state == PeerConnectionInterface::kIceConnectionCompleted ||
1073 state == PeerConnectionInterface::kIceConnectionFailed);
1074 break;
1075 case PeerConnectionInterface::kIceConnectionClosed:
1076 ASSERT(false);
1077 break;
1078 default:
1079 ASSERT(false);
1080 break;
1081 }
1082
1083 ice_connection_state_ = state;
1084 if (ice_observer_) {
1085 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1086 }
1087}
1088
1089void WebRtcSession::OnTransportRequestSignaling(
1090 cricket::Transport* transport) {
1091 ASSERT(signaling_thread()->IsCurrent());
1092 transport->OnSignalingReady();
1093 if (ice_observer_) {
1094 ice_observer_->OnIceGatheringChange(
1095 PeerConnectionInterface::kIceGatheringGathering);
1096 }
1097}
1098
1099void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1100 ASSERT(signaling_thread()->IsCurrent());
1101 // start monitoring for the write state of the transport.
1102 OnTransportWritable(transport);
1103}
1104
1105void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1106 ASSERT(signaling_thread()->IsCurrent());
1107 // TODO(bemasc): Expose more API from Transport to detect when
1108 // candidate selection starts or stops, due to success or failure.
1109 if (transport->all_channels_writable()) {
1110 if (ice_connection_state_ ==
1111 PeerConnectionInterface::kIceConnectionChecking ||
1112 ice_connection_state_ ==
1113 PeerConnectionInterface::kIceConnectionDisconnected) {
1114 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
1115 }
1116 } else if (transport->HasChannels()) {
1117 // If the current state is Connected or Completed, then there were writable
1118 // channels but now there are not, so the next state must be Disconnected.
1119 if (ice_connection_state_ ==
1120 PeerConnectionInterface::kIceConnectionConnected ||
1121 ice_connection_state_ ==
1122 PeerConnectionInterface::kIceConnectionCompleted) {
1123 SetIceConnectionState(
1124 PeerConnectionInterface::kIceConnectionDisconnected);
1125 }
1126 }
1127}
1128
1129void WebRtcSession::OnTransportProxyCandidatesReady(
1130 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1131 ASSERT(signaling_thread()->IsCurrent());
1132 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1133}
1134
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001135void WebRtcSession::OnCandidatesAllocationDone() {
1136 ASSERT(signaling_thread()->IsCurrent());
1137 if (ice_observer_) {
1138 ice_observer_->OnIceGatheringChange(
1139 PeerConnectionInterface::kIceGatheringComplete);
1140 ice_observer_->OnIceComplete();
1141 }
1142}
1143
1144// Enabling voice and video channel.
1145void WebRtcSession::EnableChannels() {
1146 if (voice_channel_ && !voice_channel_->enabled())
1147 voice_channel_->Enable(true);
1148
1149 if (video_channel_ && !video_channel_->enabled())
1150 video_channel_->Enable(true);
1151
1152 if (data_channel_.get() && !data_channel_->enabled())
1153 data_channel_->Enable(true);
1154}
1155
1156void WebRtcSession::ProcessNewLocalCandidate(
1157 const std::string& content_name,
1158 const cricket::Candidates& candidates) {
1159 int sdp_mline_index;
1160 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1161 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1162 << content_name << " not found";
1163 return;
1164 }
1165
1166 for (cricket::Candidates::const_iterator citer = candidates.begin();
1167 citer != candidates.end(); ++citer) {
1168 // Use content_name as the candidate media id.
1169 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1170 if (ice_observer_) {
1171 ice_observer_->OnIceCandidate(&candidate);
1172 }
1173 if (local_desc_) {
1174 local_desc_->AddCandidate(&candidate);
1175 }
1176 }
1177}
1178
1179// Returns the media index for a local ice candidate given the content name.
1180bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1181 int* sdp_mline_index) {
1182 if (!BaseSession::local_description() || !sdp_mline_index)
1183 return false;
1184
1185 bool content_found = false;
1186 const ContentInfos& contents = BaseSession::local_description()->contents();
1187 for (size_t index = 0; index < contents.size(); ++index) {
1188 if (contents[index].name == content_name) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001189 *sdp_mline_index = static_cast<int>(index);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001190 content_found = true;
1191 break;
1192 }
1193 }
1194 return content_found;
1195}
1196
1197bool WebRtcSession::UseCandidatesInSessionDescription(
1198 const SessionDescriptionInterface* remote_desc) {
1199 if (!remote_desc)
1200 return true;
1201 bool ret = true;
1202 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1203 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1204 for (size_t n = 0; n < candidates->count(); ++n) {
1205 ret = UseCandidate(candidates->at(n));
1206 if (!ret)
1207 break;
1208 }
1209 }
1210 return ret;
1211}
1212
1213bool WebRtcSession::UseCandidate(
1214 const IceCandidateInterface* candidate) {
1215
1216 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
1217 size_t remote_content_size =
1218 BaseSession::remote_description()->contents().size();
1219 if (mediacontent_index >= remote_content_size) {
1220 LOG(LS_ERROR)
1221 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1222 return false;
1223 }
1224
1225 cricket::ContentInfo content =
1226 BaseSession::remote_description()->contents()[mediacontent_index];
1227 std::vector<cricket::Candidate> candidates;
1228 candidates.push_back(candidate->candidate());
1229 // Invoking BaseSession method to handle remote candidates.
1230 std::string error;
1231 if (OnRemoteCandidates(content.name, candidates, &error)) {
1232 // Candidates successfully submitted for checking.
1233 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1234 ice_connection_state_ ==
1235 PeerConnectionInterface::kIceConnectionDisconnected) {
1236 // If state is New, then the session has just gotten its first remote ICE
1237 // candidates, so go to Checking.
1238 // If state is Disconnected, the session is re-using old candidates or
1239 // receiving additional ones, so go to Checking.
1240 // If state is Connected, stay Connected.
1241 // TODO(bemasc): If state is Connected, and the new candidates are for a
1242 // newly added transport, then the state actually _should_ move to
1243 // checking. Add a way to distinguish that case.
1244 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1245 }
1246 // TODO(bemasc): If state is Completed, go back to Connected.
1247 } else {
1248 LOG(LS_WARNING) << error;
1249 }
1250 return true;
1251}
1252
1253void WebRtcSession::RemoveUnusedChannelsAndTransports(
1254 const SessionDescription* desc) {
1255 const cricket::ContentInfo* voice_info =
1256 cricket::GetFirstAudioContent(desc);
1257 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1258 mediastream_signaling_->OnAudioChannelClose();
1259 SignalVoiceChannelDestroyed();
1260 const std::string content_name = voice_channel_->content_name();
1261 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
1262 DestroyTransportProxy(content_name);
1263 }
1264
1265 const cricket::ContentInfo* video_info =
1266 cricket::GetFirstVideoContent(desc);
1267 if ((!video_info || video_info->rejected) && video_channel_) {
1268 mediastream_signaling_->OnVideoChannelClose();
1269 SignalVideoChannelDestroyed();
1270 const std::string content_name = video_channel_->content_name();
1271 channel_manager_->DestroyVideoChannel(video_channel_.release());
1272 DestroyTransportProxy(content_name);
1273 }
1274
1275 const cricket::ContentInfo* data_info =
1276 cricket::GetFirstDataContent(desc);
1277 if ((!data_info || data_info->rejected) && data_channel_) {
1278 mediastream_signaling_->OnDataChannelClose();
1279 SignalDataChannelDestroyed();
1280 const std::string content_name = data_channel_->content_name();
1281 channel_manager_->DestroyDataChannel(data_channel_.release());
1282 DestroyTransportProxy(content_name);
1283 }
1284}
1285
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001286// TODO(mallinath) - Add a correct error code if the channels are not creatued
1287// due to BUNDLE is enabled but rtcp-mux is disabled.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001288bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
1289 // Disabling the BUNDLE flag in PortAllocator if offer disabled it.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001290 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1291 if (state() == STATE_INIT && !bundle_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001292 port_allocator()->set_flags(port_allocator()->flags() &
1293 ~cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1294 }
1295
1296 // Creating the media channels and transport proxies.
1297 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1298 if (voice && !voice->rejected && !voice_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001299 if (!CreateVoiceChannel(voice)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001300 LOG(LS_ERROR) << "Failed to create voice channel.";
1301 return false;
1302 }
1303 }
1304
1305 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1306 if (video && !video->rejected && !video_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001307 if (!CreateVideoChannel(video)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001308 LOG(LS_ERROR) << "Failed to create video channel.";
1309 return false;
1310 }
1311 }
1312
1313 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1314 if (data_channel_type_ != cricket::DCT_NONE &&
1315 data && !data->rejected && !data_channel_.get()) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001316 if (!CreateDataChannel(data)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001317 LOG(LS_ERROR) << "Failed to create data channel.";
1318 return false;
1319 }
1320 }
1321
1322 return true;
1323}
1324
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001325bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001327 this, content->name, true));
1328 return (voice_channel_ != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329}
1330
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001331bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332 video_channel_.reset(channel_manager_->CreateVideoChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001333 this, content->name, true, voice_channel_.get()));
1334 return (video_channel_ != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001335}
1336
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001337bool WebRtcSession::CreateDataChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001338 bool rtcp = (data_channel_type_ == cricket::DCT_RTP);
1339 data_channel_.reset(channel_manager_->CreateDataChannel(
wu@webrtc.org91053e72013-08-10 07:18:04 +00001340 this, content->name, rtcp, data_channel_type_));
1341 if (!data_channel_.get()) {
1342 return false;
1343 }
1344 data_channel_->SignalDataReceived.connect(
1345 this, &WebRtcSession::OnDataReceived);
1346 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347}
1348
1349void WebRtcSession::CopySavedCandidates(
1350 SessionDescriptionInterface* dest_desc) {
1351 if (!dest_desc) {
1352 ASSERT(false);
1353 return;
1354 }
1355 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1356 dest_desc->AddCandidate(saved_candidates_[i]);
1357 delete saved_candidates_[i];
1358 }
1359 saved_candidates_.clear();
1360}
1361
wu@webrtc.org91053e72013-08-10 07:18:04 +00001362// Look for OPEN messages and set up data channels in response.
1363void WebRtcSession::OnDataReceived(
1364 cricket::DataChannel* channel,
1365 const cricket::ReceiveDataParams& params,
1366 const talk_base::Buffer& payload) {
1367 if (params.type != cricket::DMT_CONTROL) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001368 return;
1369 }
1370
wu@webrtc.org91053e72013-08-10 07:18:04 +00001371 std::string label;
1372 DataChannelInit config;
1373 if (!mediastream_signaling_->ParseDataChannelOpenMessage(
1374 payload, &label, &config)) {
1375 LOG(LS_WARNING) << "Failed to parse data channel OPEN message.";
1376 return;
1377 }
1378
1379 config.negotiated = true; // This is the negotiation.
1380
1381 if (!mediastream_signaling_->AddDataChannelFromOpenMessage(
1382 label, config)) {
1383 LOG(LS_WARNING) << "Failed to create data channel from OPEN message.";
1384 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001385 }
1386}
1387
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001388// Returns false if bundle is enabled and rtcp_mux is disabled.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001389bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001390 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1391 if (!bundle_enabled)
1392 return true;
1393
1394 const cricket::ContentGroup* bundle_group =
1395 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1396 ASSERT(bundle_group != NULL);
1397
1398 const cricket::ContentInfos& contents = desc->contents();
1399 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1400 citer != contents.end(); ++citer) {
1401 const cricket::ContentInfo* content = (&*citer);
1402 ASSERT(content != NULL);
1403 if (bundle_group->HasContentName(content->name) &&
1404 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1405 if (!HasRtcpMuxEnabled(content))
1406 return false;
1407 }
1408 }
1409 // RTCP-MUX is enabled in all the contents.
1410 return true;
1411}
1412
1413bool WebRtcSession::HasRtcpMuxEnabled(
1414 const cricket::ContentInfo* content) {
1415 const cricket::MediaContentDescription* description =
1416 static_cast<cricket::MediaContentDescription*>(content->description);
1417 return description->rtcp_mux();
1418}
1419
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001420bool WebRtcSession::ValidateSessionDescription(
1421 const SessionDescriptionInterface* sdesc,
1422 cricket::ContentSource source, std::string* error_desc) {
1423
1424 if (error() != cricket::BaseSession::ERROR_NONE) {
1425 return BadSdp(source, SessionErrorMsg(error()), error_desc);
1426 }
1427
1428 if (!sdesc || !sdesc->description()) {
1429 return BadSdp(source, kInvalidSdp, error_desc);
1430 }
1431
1432 std::string type = sdesc->type();
1433 Action action = GetAction(sdesc->type());
1434 if (source == cricket::CS_LOCAL) {
1435 if (!ExpectSetLocalDescription(action))
1436 return BadSdp(source, BadStateErrMsg(type, state()), error_desc);
1437 } else {
1438 if (!ExpectSetRemoteDescription(action))
1439 return BadSdp(source, BadStateErrMsg(type, state()), error_desc);
1440 }
1441
1442 // Verify crypto settings.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001443 std::string crypto_error;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001444 if (webrtc_session_desc_factory_->secure() == cricket::SEC_REQUIRED &&
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001445 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
1446 return BadSdp(source, crypto_error, error_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001447 }
1448
1449 if (!ValidateBundleSettings(sdesc->description())) {
1450 return BadSdp(source, kBundleWithoutRtcpMux, error_desc);
1451 }
1452
1453 // Verify m-lines in Answer when compared against Offer.
1454 if (action == kAnswer) {
1455 const cricket::SessionDescription* offer_desc =
1456 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1457 local_description()->description();
1458 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
1459 return BadSdp(source, kMlineMismatch, error_desc);
1460 }
1461 }
1462
1463 return true;
1464}
1465
1466bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1467 return ((action == kOffer && state() == STATE_INIT) ||
1468 // update local offer
1469 (action == kOffer && state() == STATE_SENTINITIATE) ||
1470 // update the current ongoing session.
1471 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1472 (action == kOffer && state() == STATE_SENTACCEPT) ||
1473 (action == kOffer && state() == STATE_INPROGRESS) ||
1474 // accept remote offer
1475 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1476 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1477 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1478 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1479}
1480
1481bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1482 return ((action == kOffer && state() == STATE_INIT) ||
1483 // update remote offer
1484 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1485 // update the current ongoing session
1486 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1487 (action == kOffer && state() == STATE_SENTACCEPT) ||
1488 (action == kOffer && state() == STATE_INPROGRESS) ||
1489 // accept local offer
1490 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1491 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1492 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1493 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1494}
1495
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001496} // namespace webrtc