blob: ff331a9e06b9c0b0798e0a419504ff429b7d5ac8 [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
930talk_base::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
931 const std::string& label,
932 const DataChannelInit* config) {
933 if (state() == STATE_RECEIVEDTERMINATE) {
934 return NULL;
935 }
936 if (data_channel_type_ == cricket::DCT_NONE) {
937 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
938 return NULL;
939 }
940 DataChannelInit new_config = config ? (*config) : DataChannelInit();
941
942 if (data_channel_type_ == cricket::DCT_SCTP) {
943 if (new_config.id < 0) {
944 if (!mediastream_signaling_->AllocateSctpId(&new_config.id)) {
945 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
946 return NULL;
947 }
948 } else if (!mediastream_signaling_->IsSctpIdAvailable(new_config.id)) {
949 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
950 << "because the id is already in use or out of range.";
951 return NULL;
952 }
953 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000954
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955 talk_base::scoped_refptr<DataChannel> channel(
956 DataChannel::Create(this, label, &new_config));
957 if (channel == NULL)
958 return NULL;
959 if (!mediastream_signaling_->AddDataChannel(channel))
960 return NULL;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000961 if (data_channel_type_ == cricket::DCT_SCTP) {
962 if (config == NULL) {
963 LOG(LS_WARNING) << "Could not send data channel OPEN message"
964 << " because of NULL config.";
965 return NULL;
966 }
967 if (data_channel_.get()) {
968 channel->SetReceiveSsrc(new_config.id);
969 channel->SetSendSsrc(new_config.id);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000970 }
971 if (!config->negotiated) {
972 talk_base::Buffer *payload = new talk_base::Buffer;
973 if (!mediastream_signaling_->WriteDataChannelOpenMessage(
974 label, *config, payload)) {
975 LOG(LS_WARNING) << "Could not write data channel OPEN message";
976 }
977 // SendControl may queue the message until the data channel's set up,
978 // or congestion clears.
979 channel->SendControl(payload);
980 }
981 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000982 return channel;
983}
984
985cricket::DataChannelType WebRtcSession::data_channel_type() const {
986 return data_channel_type_;
987}
988
wu@webrtc.org91053e72013-08-10 07:18:04 +0000989bool WebRtcSession::IceRestartPending() const {
990 return ice_restart_latch_->Get();
991}
992
993void WebRtcSession::ResetIceRestartLatch() {
994 ice_restart_latch_->Reset();
995}
996
997void WebRtcSession::OnIdentityReady(talk_base::SSLIdentity* identity) {
998 SetIdentity(identity);
999}
1000
1001bool WebRtcSession::waiting_for_identity() const {
1002 return webrtc_session_desc_factory_->waiting_for_identity();
1003}
1004
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005void WebRtcSession::SetIceConnectionState(
1006 PeerConnectionInterface::IceConnectionState state) {
1007 if (ice_connection_state_ == state) {
1008 return;
1009 }
1010
1011 // ASSERT that the requested transition is allowed. Note that
1012 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1013 // within PeerConnection). This switch statement should compile away when
1014 // ASSERTs are disabled.
1015 switch (ice_connection_state_) {
1016 case PeerConnectionInterface::kIceConnectionNew:
1017 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1018 break;
1019 case PeerConnectionInterface::kIceConnectionChecking:
1020 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1021 state == PeerConnectionInterface::kIceConnectionConnected);
1022 break;
1023 case PeerConnectionInterface::kIceConnectionConnected:
1024 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1025 state == PeerConnectionInterface::kIceConnectionChecking ||
1026 state == PeerConnectionInterface::kIceConnectionCompleted);
1027 break;
1028 case PeerConnectionInterface::kIceConnectionCompleted:
1029 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1030 state == PeerConnectionInterface::kIceConnectionDisconnected);
1031 break;
1032 case PeerConnectionInterface::kIceConnectionFailed:
1033 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1034 break;
1035 case PeerConnectionInterface::kIceConnectionDisconnected:
1036 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1037 state == PeerConnectionInterface::kIceConnectionConnected ||
1038 state == PeerConnectionInterface::kIceConnectionCompleted ||
1039 state == PeerConnectionInterface::kIceConnectionFailed);
1040 break;
1041 case PeerConnectionInterface::kIceConnectionClosed:
1042 ASSERT(false);
1043 break;
1044 default:
1045 ASSERT(false);
1046 break;
1047 }
1048
1049 ice_connection_state_ = state;
1050 if (ice_observer_) {
1051 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1052 }
1053}
1054
1055void WebRtcSession::OnTransportRequestSignaling(
1056 cricket::Transport* transport) {
1057 ASSERT(signaling_thread()->IsCurrent());
1058 transport->OnSignalingReady();
1059 if (ice_observer_) {
1060 ice_observer_->OnIceGatheringChange(
1061 PeerConnectionInterface::kIceGatheringGathering);
1062 }
1063}
1064
1065void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1066 ASSERT(signaling_thread()->IsCurrent());
1067 // start monitoring for the write state of the transport.
1068 OnTransportWritable(transport);
1069}
1070
1071void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1072 ASSERT(signaling_thread()->IsCurrent());
1073 // TODO(bemasc): Expose more API from Transport to detect when
1074 // candidate selection starts or stops, due to success or failure.
1075 if (transport->all_channels_writable()) {
1076 if (ice_connection_state_ ==
1077 PeerConnectionInterface::kIceConnectionChecking ||
1078 ice_connection_state_ ==
1079 PeerConnectionInterface::kIceConnectionDisconnected) {
1080 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
1081 }
1082 } else if (transport->HasChannels()) {
1083 // If the current state is Connected or Completed, then there were writable
1084 // channels but now there are not, so the next state must be Disconnected.
1085 if (ice_connection_state_ ==
1086 PeerConnectionInterface::kIceConnectionConnected ||
1087 ice_connection_state_ ==
1088 PeerConnectionInterface::kIceConnectionCompleted) {
1089 SetIceConnectionState(
1090 PeerConnectionInterface::kIceConnectionDisconnected);
1091 }
1092 }
1093}
1094
1095void WebRtcSession::OnTransportProxyCandidatesReady(
1096 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1097 ASSERT(signaling_thread()->IsCurrent());
1098 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1099}
1100
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101void WebRtcSession::OnCandidatesAllocationDone() {
1102 ASSERT(signaling_thread()->IsCurrent());
1103 if (ice_observer_) {
1104 ice_observer_->OnIceGatheringChange(
1105 PeerConnectionInterface::kIceGatheringComplete);
1106 ice_observer_->OnIceComplete();
1107 }
1108}
1109
1110// Enabling voice and video channel.
1111void WebRtcSession::EnableChannels() {
1112 if (voice_channel_ && !voice_channel_->enabled())
1113 voice_channel_->Enable(true);
1114
1115 if (video_channel_ && !video_channel_->enabled())
1116 video_channel_->Enable(true);
1117
1118 if (data_channel_.get() && !data_channel_->enabled())
1119 data_channel_->Enable(true);
1120}
1121
1122void WebRtcSession::ProcessNewLocalCandidate(
1123 const std::string& content_name,
1124 const cricket::Candidates& candidates) {
1125 int sdp_mline_index;
1126 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1127 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1128 << content_name << " not found";
1129 return;
1130 }
1131
1132 for (cricket::Candidates::const_iterator citer = candidates.begin();
1133 citer != candidates.end(); ++citer) {
1134 // Use content_name as the candidate media id.
1135 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1136 if (ice_observer_) {
1137 ice_observer_->OnIceCandidate(&candidate);
1138 }
1139 if (local_desc_) {
1140 local_desc_->AddCandidate(&candidate);
1141 }
1142 }
1143}
1144
1145// Returns the media index for a local ice candidate given the content name.
1146bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1147 int* sdp_mline_index) {
1148 if (!BaseSession::local_description() || !sdp_mline_index)
1149 return false;
1150
1151 bool content_found = false;
1152 const ContentInfos& contents = BaseSession::local_description()->contents();
1153 for (size_t index = 0; index < contents.size(); ++index) {
1154 if (contents[index].name == content_name) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001155 *sdp_mline_index = static_cast<int>(index);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001156 content_found = true;
1157 break;
1158 }
1159 }
1160 return content_found;
1161}
1162
1163bool WebRtcSession::UseCandidatesInSessionDescription(
1164 const SessionDescriptionInterface* remote_desc) {
1165 if (!remote_desc)
1166 return true;
1167 bool ret = true;
1168 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1169 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1170 for (size_t n = 0; n < candidates->count(); ++n) {
1171 ret = UseCandidate(candidates->at(n));
1172 if (!ret)
1173 break;
1174 }
1175 }
1176 return ret;
1177}
1178
1179bool WebRtcSession::UseCandidate(
1180 const IceCandidateInterface* candidate) {
1181
1182 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
1183 size_t remote_content_size =
1184 BaseSession::remote_description()->contents().size();
1185 if (mediacontent_index >= remote_content_size) {
1186 LOG(LS_ERROR)
1187 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1188 return false;
1189 }
1190
1191 cricket::ContentInfo content =
1192 BaseSession::remote_description()->contents()[mediacontent_index];
1193 std::vector<cricket::Candidate> candidates;
1194 candidates.push_back(candidate->candidate());
1195 // Invoking BaseSession method to handle remote candidates.
1196 std::string error;
1197 if (OnRemoteCandidates(content.name, candidates, &error)) {
1198 // Candidates successfully submitted for checking.
1199 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1200 ice_connection_state_ ==
1201 PeerConnectionInterface::kIceConnectionDisconnected) {
1202 // If state is New, then the session has just gotten its first remote ICE
1203 // candidates, so go to Checking.
1204 // If state is Disconnected, the session is re-using old candidates or
1205 // receiving additional ones, so go to Checking.
1206 // If state is Connected, stay Connected.
1207 // TODO(bemasc): If state is Connected, and the new candidates are for a
1208 // newly added transport, then the state actually _should_ move to
1209 // checking. Add a way to distinguish that case.
1210 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1211 }
1212 // TODO(bemasc): If state is Completed, go back to Connected.
1213 } else {
1214 LOG(LS_WARNING) << error;
1215 }
1216 return true;
1217}
1218
1219void WebRtcSession::RemoveUnusedChannelsAndTransports(
1220 const SessionDescription* desc) {
1221 const cricket::ContentInfo* voice_info =
1222 cricket::GetFirstAudioContent(desc);
1223 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1224 mediastream_signaling_->OnAudioChannelClose();
1225 SignalVoiceChannelDestroyed();
1226 const std::string content_name = voice_channel_->content_name();
1227 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
1228 DestroyTransportProxy(content_name);
1229 }
1230
1231 const cricket::ContentInfo* video_info =
1232 cricket::GetFirstVideoContent(desc);
1233 if ((!video_info || video_info->rejected) && video_channel_) {
1234 mediastream_signaling_->OnVideoChannelClose();
1235 SignalVideoChannelDestroyed();
1236 const std::string content_name = video_channel_->content_name();
1237 channel_manager_->DestroyVideoChannel(video_channel_.release());
1238 DestroyTransportProxy(content_name);
1239 }
1240
1241 const cricket::ContentInfo* data_info =
1242 cricket::GetFirstDataContent(desc);
1243 if ((!data_info || data_info->rejected) && data_channel_) {
1244 mediastream_signaling_->OnDataChannelClose();
1245 SignalDataChannelDestroyed();
1246 const std::string content_name = data_channel_->content_name();
1247 channel_manager_->DestroyDataChannel(data_channel_.release());
1248 DestroyTransportProxy(content_name);
1249 }
1250}
1251
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001252// TODO(mallinath) - Add a correct error code if the channels are not creatued
1253// due to BUNDLE is enabled but rtcp-mux is disabled.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001254bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
1255 // Disabling the BUNDLE flag in PortAllocator if offer disabled it.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001256 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1257 if (state() == STATE_INIT && !bundle_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001258 port_allocator()->set_flags(port_allocator()->flags() &
1259 ~cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1260 }
1261
1262 // Creating the media channels and transport proxies.
1263 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1264 if (voice && !voice->rejected && !voice_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001265 if (!CreateVoiceChannel(voice)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001266 LOG(LS_ERROR) << "Failed to create voice channel.";
1267 return false;
1268 }
1269 }
1270
1271 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1272 if (video && !video->rejected && !video_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001273 if (!CreateVideoChannel(video)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001274 LOG(LS_ERROR) << "Failed to create video channel.";
1275 return false;
1276 }
1277 }
1278
1279 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1280 if (data_channel_type_ != cricket::DCT_NONE &&
1281 data && !data->rejected && !data_channel_.get()) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001282 if (!CreateDataChannel(data)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283 LOG(LS_ERROR) << "Failed to create data channel.";
1284 return false;
1285 }
1286 }
1287
1288 return true;
1289}
1290
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001291bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001292 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001293 this, content->name, true));
1294 return (voice_channel_ != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295}
1296
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001297bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001298 video_channel_.reset(channel_manager_->CreateVideoChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001299 this, content->name, true, voice_channel_.get()));
1300 return (video_channel_ != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001301}
1302
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001303bool WebRtcSession::CreateDataChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001304 bool rtcp = (data_channel_type_ == cricket::DCT_RTP);
1305 data_channel_.reset(channel_manager_->CreateDataChannel(
wu@webrtc.org91053e72013-08-10 07:18:04 +00001306 this, content->name, rtcp, data_channel_type_));
1307 if (!data_channel_.get()) {
1308 return false;
1309 }
1310 data_channel_->SignalDataReceived.connect(
1311 this, &WebRtcSession::OnDataReceived);
1312 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313}
1314
1315void WebRtcSession::CopySavedCandidates(
1316 SessionDescriptionInterface* dest_desc) {
1317 if (!dest_desc) {
1318 ASSERT(false);
1319 return;
1320 }
1321 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1322 dest_desc->AddCandidate(saved_candidates_[i]);
1323 delete saved_candidates_[i];
1324 }
1325 saved_candidates_.clear();
1326}
1327
wu@webrtc.org91053e72013-08-10 07:18:04 +00001328// Look for OPEN messages and set up data channels in response.
1329void WebRtcSession::OnDataReceived(
1330 cricket::DataChannel* channel,
1331 const cricket::ReceiveDataParams& params,
1332 const talk_base::Buffer& payload) {
1333 if (params.type != cricket::DMT_CONTROL) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001334 return;
1335 }
1336
wu@webrtc.org91053e72013-08-10 07:18:04 +00001337 std::string label;
1338 DataChannelInit config;
1339 if (!mediastream_signaling_->ParseDataChannelOpenMessage(
1340 payload, &label, &config)) {
1341 LOG(LS_WARNING) << "Failed to parse data channel OPEN message.";
1342 return;
1343 }
1344
1345 config.negotiated = true; // This is the negotiation.
1346
1347 if (!mediastream_signaling_->AddDataChannelFromOpenMessage(
1348 label, config)) {
1349 LOG(LS_WARNING) << "Failed to create data channel from OPEN message.";
1350 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351 }
1352}
1353
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001354// Returns false if bundle is enabled and rtcp_mux is disabled.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001355bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001356 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1357 if (!bundle_enabled)
1358 return true;
1359
1360 const cricket::ContentGroup* bundle_group =
1361 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1362 ASSERT(bundle_group != NULL);
1363
1364 const cricket::ContentInfos& contents = desc->contents();
1365 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1366 citer != contents.end(); ++citer) {
1367 const cricket::ContentInfo* content = (&*citer);
1368 ASSERT(content != NULL);
1369 if (bundle_group->HasContentName(content->name) &&
1370 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1371 if (!HasRtcpMuxEnabled(content))
1372 return false;
1373 }
1374 }
1375 // RTCP-MUX is enabled in all the contents.
1376 return true;
1377}
1378
1379bool WebRtcSession::HasRtcpMuxEnabled(
1380 const cricket::ContentInfo* content) {
1381 const cricket::MediaContentDescription* description =
1382 static_cast<cricket::MediaContentDescription*>(content->description);
1383 return description->rtcp_mux();
1384}
1385
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001386bool WebRtcSession::ValidateSessionDescription(
1387 const SessionDescriptionInterface* sdesc,
1388 cricket::ContentSource source, std::string* error_desc) {
1389
1390 if (error() != cricket::BaseSession::ERROR_NONE) {
1391 return BadSdp(source, SessionErrorMsg(error()), error_desc);
1392 }
1393
1394 if (!sdesc || !sdesc->description()) {
1395 return BadSdp(source, kInvalidSdp, error_desc);
1396 }
1397
1398 std::string type = sdesc->type();
1399 Action action = GetAction(sdesc->type());
1400 if (source == cricket::CS_LOCAL) {
1401 if (!ExpectSetLocalDescription(action))
1402 return BadSdp(source, BadStateErrMsg(type, state()), error_desc);
1403 } else {
1404 if (!ExpectSetRemoteDescription(action))
1405 return BadSdp(source, BadStateErrMsg(type, state()), error_desc);
1406 }
1407
1408 // Verify crypto settings.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001409 std::string crypto_error;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001410 if (webrtc_session_desc_factory_->secure() == cricket::SEC_REQUIRED &&
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001411 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
1412 return BadSdp(source, crypto_error, error_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001413 }
1414
1415 if (!ValidateBundleSettings(sdesc->description())) {
1416 return BadSdp(source, kBundleWithoutRtcpMux, error_desc);
1417 }
1418
1419 // Verify m-lines in Answer when compared against Offer.
1420 if (action == kAnswer) {
1421 const cricket::SessionDescription* offer_desc =
1422 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1423 local_description()->description();
1424 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
1425 return BadSdp(source, kMlineMismatch, error_desc);
1426 }
1427 }
1428
1429 return true;
1430}
1431
1432bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1433 return ((action == kOffer && state() == STATE_INIT) ||
1434 // update local offer
1435 (action == kOffer && state() == STATE_SENTINITIATE) ||
1436 // update the current ongoing session.
1437 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1438 (action == kOffer && state() == STATE_SENTACCEPT) ||
1439 (action == kOffer && state() == STATE_INPROGRESS) ||
1440 // accept remote offer
1441 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1442 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1443 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1444 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1445}
1446
1447bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1448 return ((action == kOffer && state() == STATE_INIT) ||
1449 // update remote offer
1450 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1451 // update the current ongoing session
1452 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1453 (action == kOffer && state() == STATE_SENTACCEPT) ||
1454 (action == kOffer && state() == STATE_INPROGRESS) ||
1455 // accept local offer
1456 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1457 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1458 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1459 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1460}
1461
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001462} // namespace webrtc