3 * Copyright 2012, Google Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
28 #include "talk/app/webrtc/webrtcsession.h"
35 #include "talk/app/webrtc/jsepicecandidate.h"
36 #include "talk/app/webrtc/jsepsessiondescription.h"
37 #include "talk/app/webrtc/mediaconstraintsinterface.h"
38 #include "talk/app/webrtc/mediastreamsignaling.h"
39 #include "talk/app/webrtc/peerconnectioninterface.h"
40 #include "talk/app/webrtc/webrtcsessiondescriptionfactory.h"
41 #include "talk/base/helpers.h"
42 #include "talk/base/logging.h"
43 #include "talk/base/stringencode.h"
44 #include "talk/base/stringutils.h"
45 #include "talk/media/base/constants.h"
46 #include "talk/media/base/videocapturer.h"
47 #include "talk/session/media/channel.h"
48 #include "talk/session/media/channelmanager.h"
49 #include "talk/session/media/mediasession.h"
51 using cricket::ContentInfo;
52 using cricket::ContentInfos;
53 using cricket::MediaContentDescription;
54 using cricket::SessionDescription;
55 using cricket::TransportInfo;
60 const char kBundleWithoutRtcpMux[] = "RTCP-MUX must be enabled when BUNDLE "
62 const char kCreateChannelFailed[] = "Failed to create channels.";
63 const char kInvalidCandidates[] = "Description contains invalid candidates.";
64 const char kInvalidSdp[] = "Invalid session description.";
65 const char kMlineMismatch[] =
66 "Offer and answer descriptions m-lines are not matching. Rejecting answer.";
67 const char kPushDownTDFailed[] =
68 "Failed to push down transport description:";
69 const char kSdpWithoutDtlsFingerprint[] =
70 "Called with SDP without DTLS fingerprint.";
71 const char kSdpWithoutSdesCrypto[] =
72 "Called with SDP without SDES crypto.";
73 const char kSdpWithoutIceUfragPwd[] =
74 "Called with SDP without ice-ufrag and ice-pwd.";
75 const char kSessionError[] = "Session error code: ";
76 const char kSessionErrorDesc[] = "Session error description: ";
78 // Compares |answer| against |offer|. Comparision is done
79 // for number of m-lines in answer against offer. If matches true will be
80 // returned otherwise false.
81 static bool VerifyMediaDescriptions(
82 const SessionDescription* answer, const SessionDescription* offer) {
83 if (offer->contents().size() != answer->contents().size())
86 for (size_t i = 0; i < offer->contents().size(); ++i) {
87 if ((offer->contents()[i].name) != answer->contents()[i].name) {
90 const MediaContentDescription* offer_mdesc =
91 static_cast<const MediaContentDescription*>(
92 offer->contents()[i].description);
93 const MediaContentDescription* answer_mdesc =
94 static_cast<const MediaContentDescription*>(
95 answer->contents()[i].description);
96 if (offer_mdesc->type() != answer_mdesc->type()) {
103 // Checks that each non-rejected content has SDES crypto keys or a DTLS
104 // fingerprint. Mismatches, such as replying with a DTLS fingerprint to SDES
105 // keys, will be caught in Transport negotiation, and backstopped by Channel's
106 // |secure_required| check.
107 static bool VerifyCrypto(const SessionDescription* desc,
109 std::string* error) {
110 const ContentInfos& contents = desc->contents();
111 for (size_t index = 0; index < contents.size(); ++index) {
112 const ContentInfo* cinfo = &contents[index];
113 if (cinfo->rejected) {
117 // If the content isn't rejected, crypto must be present.
118 const MediaContentDescription* media =
119 static_cast<const MediaContentDescription*>(cinfo->description);
120 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
121 if (!media || !tinfo) {
122 // Something is not right.
123 LOG(LS_ERROR) << kInvalidSdp;
124 *error = kInvalidSdp;
128 if (!tinfo->description.identity_fingerprint) {
130 "Session description must have DTLS fingerprint if DTLS enabled.";
131 *error = kSdpWithoutDtlsFingerprint;
135 if (media->cryptos().empty()) {
137 "Session description must have SDES when DTLS disabled.";
138 *error = kSdpWithoutSdesCrypto;
147 // Checks that each non-rejected content has ice-ufrag and ice-pwd set.
148 static bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
149 const ContentInfos& contents = desc->contents();
150 for (size_t index = 0; index < contents.size(); ++index) {
151 const ContentInfo* cinfo = &contents[index];
152 if (cinfo->rejected) {
156 // If the content isn't rejected, ice-ufrag and ice-pwd must be present.
157 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
159 // Something is not right.
160 LOG(LS_ERROR) << kInvalidSdp;
163 if (tinfo->description.ice_ufrag.empty() ||
164 tinfo->description.ice_pwd.empty()) {
165 LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
172 // Forces |sdesc->crypto_required| to the appropriate state based on the
173 // current security policy, to ensure a failure occurs if there is an error
174 // in crypto negotiation.
175 // Called when processing the local session description.
176 static void UpdateSessionDescriptionSecurePolicy(cricket::CryptoType type,
177 SessionDescription* sdesc) {
182 // Updating the |crypto_required_| in MediaContentDescription to the
183 // appropriate state based on the current security policy.
184 for (cricket::ContentInfos::iterator iter = sdesc->contents().begin();
185 iter != sdesc->contents().end(); ++iter) {
186 if (cricket::IsMediaContent(&*iter)) {
187 MediaContentDescription* mdesc =
188 static_cast<MediaContentDescription*> (iter->description);
190 mdesc->set_crypto_required(type);
196 static bool GetAudioSsrcByTrackId(
197 const SessionDescription* session_description,
198 const std::string& track_id, uint32 *ssrc) {
199 const cricket::ContentInfo* audio_info =
200 cricket::GetFirstAudioContent(session_description);
202 LOG(LS_ERROR) << "Audio not used in this call";
206 const cricket::MediaContentDescription* audio_content =
207 static_cast<const cricket::MediaContentDescription*>(
208 audio_info->description);
209 cricket::StreamParams stream;
210 if (!cricket::GetStreamByIds(audio_content->streams(), "", track_id,
214 *ssrc = stream.first_ssrc();
218 static bool GetTrackIdBySsrc(const SessionDescription* session_description,
219 uint32 ssrc, std::string* track_id) {
220 ASSERT(track_id != NULL);
222 cricket::StreamParams stream_out;
223 const cricket::ContentInfo* audio_info =
224 cricket::GetFirstAudioContent(session_description);
228 const cricket::MediaContentDescription* audio_content =
229 static_cast<const cricket::MediaContentDescription*>(
230 audio_info->description);
232 if (cricket::GetStreamBySsrc(audio_content->streams(), ssrc, &stream_out)) {
233 *track_id = stream_out.id;
237 const cricket::ContentInfo* video_info =
238 cricket::GetFirstVideoContent(session_description);
242 const cricket::MediaContentDescription* video_content =
243 static_cast<const cricket::MediaContentDescription*>(
244 video_info->description);
246 if (cricket::GetStreamBySsrc(video_content->streams(), ssrc, &stream_out)) {
247 *track_id = stream_out.id;
253 static bool BadSdp(const std::string& source,
254 const std::string& type,
255 const std::string& reason,
256 std::string* err_desc) {
257 std::ostringstream desc;
258 desc << "Failed to set " << source << " " << type << " sdp: " << reason;
261 *err_desc = desc.str();
263 LOG(LS_ERROR) << desc.str();
267 static bool BadSdp(cricket::ContentSource source,
268 const std::string& type,
269 const std::string& reason,
270 std::string* err_desc) {
271 if (source == cricket::CS_LOCAL) {
272 return BadSdp("local", type, reason, err_desc);
274 return BadSdp("remote", type, reason, err_desc);
278 static bool BadLocalSdp(const std::string& type,
279 const std::string& reason,
280 std::string* err_desc) {
281 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
284 static bool BadRemoteSdp(const std::string& type,
285 const std::string& reason,
286 std::string* err_desc) {
287 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
290 static bool BadOfferSdp(cricket::ContentSource source,
291 const std::string& reason,
292 std::string* err_desc) {
293 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
296 static bool BadPranswerSdp(cricket::ContentSource source,
297 const std::string& reason,
298 std::string* err_desc) {
299 return BadSdp(source, SessionDescriptionInterface::kPrAnswer,
303 static bool BadAnswerSdp(cricket::ContentSource source,
304 const std::string& reason,
305 std::string* err_desc) {
306 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
309 #define GET_STRING_OF_STATE(state) \
310 case cricket::BaseSession::state: \
314 static std::string GetStateString(cricket::BaseSession::State state) {
317 GET_STRING_OF_STATE(STATE_INIT)
318 GET_STRING_OF_STATE(STATE_SENTINITIATE)
319 GET_STRING_OF_STATE(STATE_RECEIVEDINITIATE)
320 GET_STRING_OF_STATE(STATE_SENTPRACCEPT)
321 GET_STRING_OF_STATE(STATE_SENTACCEPT)
322 GET_STRING_OF_STATE(STATE_RECEIVEDPRACCEPT)
323 GET_STRING_OF_STATE(STATE_RECEIVEDACCEPT)
324 GET_STRING_OF_STATE(STATE_SENTMODIFY)
325 GET_STRING_OF_STATE(STATE_RECEIVEDMODIFY)
326 GET_STRING_OF_STATE(STATE_SENTREJECT)
327 GET_STRING_OF_STATE(STATE_RECEIVEDREJECT)
328 GET_STRING_OF_STATE(STATE_SENTREDIRECT)
329 GET_STRING_OF_STATE(STATE_SENTTERMINATE)
330 GET_STRING_OF_STATE(STATE_RECEIVEDTERMINATE)
331 GET_STRING_OF_STATE(STATE_INPROGRESS)
332 GET_STRING_OF_STATE(STATE_DEINIT)
340 #define GET_STRING_OF_ERROR_CODE(err) \
341 case cricket::BaseSession::err: \
345 static std::string GetErrorCodeString(cricket::BaseSession::Error err) {
348 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
349 GET_STRING_OF_ERROR_CODE(ERROR_TIME)
350 GET_STRING_OF_ERROR_CODE(ERROR_RESPONSE)
351 GET_STRING_OF_ERROR_CODE(ERROR_NETWORK)
352 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
353 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
361 static std::string MakeErrorString(const std::string& error,
362 const std::string& desc) {
363 std::ostringstream ret;
364 ret << error << " " << desc;
368 static std::string MakeTdErrorString(const std::string& desc) {
369 return MakeErrorString(kPushDownTDFailed, desc);
372 // Set |option| to the highest-priority value of |key| in the optional
373 // constraints if the key is found and has a valid value.
374 static void SetOptionFromOptionalConstraint(
375 const MediaConstraintsInterface* constraints,
376 const std::string& key, cricket::Settable<int>* option) {
380 std::string string_value;
382 if (constraints->GetOptional().FindFirst(key, &string_value)) {
383 if (talk_base::FromString(string_value, &value)) {
389 // Help class used to remember if a a remote peer has requested ice restart by
390 // by sending a description with new ice ufrag and password.
391 class IceRestartAnswerLatch {
393 IceRestartAnswerLatch() : ice_restart_(false) { }
395 // Returns true if CheckForRemoteIceRestart has been called with a new session
396 // description where ice password and ufrag has changed since last time
397 // Reset() was called.
404 ice_restart_ = false;
408 void CheckForRemoteIceRestart(
409 const SessionDescriptionInterface* old_desc,
410 const SessionDescriptionInterface* new_desc) {
411 if (!old_desc || new_desc->type() != SessionDescriptionInterface::kOffer) {
414 const SessionDescription* new_sd = new_desc->description();
415 const SessionDescription* old_sd = old_desc->description();
416 const ContentInfos& contents = new_sd->contents();
417 for (size_t index = 0; index < contents.size(); ++index) {
418 const ContentInfo* cinfo = &contents[index];
419 if (cinfo->rejected) {
422 // If the content isn't rejected, check if ufrag and password has
424 const cricket::TransportDescription* new_transport_desc =
425 new_sd->GetTransportDescriptionByName(cinfo->name);
426 const cricket::TransportDescription* old_transport_desc =
427 old_sd->GetTransportDescriptionByName(cinfo->name);
428 if (!new_transport_desc || !old_transport_desc) {
429 // No transport description exist. This is not an ice restart.
432 if (new_transport_desc->ice_pwd != old_transport_desc->ice_pwd &&
433 new_transport_desc->ice_ufrag != old_transport_desc->ice_ufrag) {
434 LOG(LS_INFO) << "Remote peer request ice restart.";
445 WebRtcSession::WebRtcSession(
446 cricket::ChannelManager* channel_manager,
447 talk_base::Thread* signaling_thread,
448 talk_base::Thread* worker_thread,
449 cricket::PortAllocator* port_allocator,
450 MediaStreamSignaling* mediastream_signaling)
451 : cricket::BaseSession(signaling_thread, worker_thread, port_allocator,
452 talk_base::ToString(talk_base::CreateRandomId64() &
454 cricket::NS_JINGLE_RTP, false),
455 // RFC 3264: The numeric value of the session id and version in the
456 // o line MUST be representable with a "64 bit signed integer".
457 // Due to this constraint session id |sid_| is max limited to LLONG_MAX.
458 channel_manager_(channel_manager),
459 mediastream_signaling_(mediastream_signaling),
461 ice_connection_state_(PeerConnectionInterface::kIceConnectionNew),
462 older_version_remote_peer_(false),
463 dtls_enabled_(false),
464 data_channel_type_(cricket::DCT_NONE),
465 ice_restart_latch_(new IceRestartAnswerLatch) {
468 WebRtcSession::~WebRtcSession() {
469 if (voice_channel_.get()) {
470 SignalVoiceChannelDestroyed();
471 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
473 if (video_channel_.get()) {
474 SignalVideoChannelDestroyed();
475 channel_manager_->DestroyVideoChannel(video_channel_.release());
477 if (data_channel_.get()) {
478 SignalDataChannelDestroyed();
479 channel_manager_->DestroyDataChannel(data_channel_.release());
481 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
482 delete saved_candidates_[i];
487 bool WebRtcSession::Initialize(
488 const PeerConnectionFactoryInterface::Options& options,
489 const MediaConstraintsInterface* constraints,
490 DTLSIdentityServiceInterface* dtls_identity_service,
491 PeerConnectionInterface::IceTransportsType ice_transport) {
492 // TODO(perkj): Take |constraints| into consideration. Return false if not all
493 // mandatory constraints can be fulfilled. Note that |constraints|
497 if (options.disable_encryption) {
498 dtls_enabled_ = false;
500 // Enable DTLS by default if |dtls_identity_service| is valid.
501 dtls_enabled_ = (dtls_identity_service != NULL);
502 // |constraints| can override the default |dtls_enabled_| value.
505 MediaConstraintsInterface::kEnableDtlsSrtp,
507 dtls_enabled_ = value;
511 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
512 // It takes precendence over the disable_sctp_data_channels
513 // PeerConnectionFactoryInterface::Options.
515 constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
516 &value, NULL) && value) {
517 LOG(LS_INFO) << "Allowing RTP data engine.";
518 data_channel_type_ = cricket::DCT_RTP;
520 // DTLS has to be enabled to use SCTP.
521 if (!options.disable_sctp_data_channels && dtls_enabled_) {
522 LOG(LS_INFO) << "Allowing SCTP data engine.";
523 data_channel_type_ = cricket::DCT_SCTP;
526 if (data_channel_type_ != cricket::DCT_NONE) {
527 mediastream_signaling_->SetDataChannelFactory(this);
530 // Find DSCP constraint.
533 MediaConstraintsInterface::kEnableDscp,
535 audio_options_.dscp.Set(value);
536 video_options_.dscp.Set(value);
539 // Find Suspend Below Min Bitrate constraint.
542 MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate,
545 video_options_.suspend_below_min_bitrate.Set(value);
550 MediaConstraintsInterface::kSkipEncodingUnusedStreams,
553 video_options_.skip_encoding_unused_streams.Set(value);
556 SetOptionFromOptionalConstraint(constraints,
557 MediaConstraintsInterface::kScreencastMinBitrate,
558 &video_options_.screencast_min_bitrate);
560 // Find constraints for cpu overuse detection.
561 SetOptionFromOptionalConstraint(constraints,
562 MediaConstraintsInterface::kCpuUnderuseThreshold,
563 &video_options_.cpu_underuse_threshold);
564 SetOptionFromOptionalConstraint(constraints,
565 MediaConstraintsInterface::kCpuOveruseThreshold,
566 &video_options_.cpu_overuse_threshold);
570 MediaConstraintsInterface::kCpuOveruseDetection,
573 video_options_.cpu_overuse_detection.Set(value);
577 MediaConstraintsInterface::kCpuOveruseEncodeUsage,
580 video_options_.cpu_overuse_encode_usage.Set(value);
583 // Find improved wifi bwe constraint.
586 MediaConstraintsInterface::kImprovedWifiBwe,
589 video_options_.use_improved_wifi_bandwidth_estimator.Set(value);
591 // Enable by default if the constraint is not set.
592 video_options_.use_improved_wifi_bandwidth_estimator.Set(true);
597 MediaConstraintsInterface::kHighStartBitrate,
600 video_options_.video_start_bitrate.Set(cricket::kHighStartBitrate);
605 MediaConstraintsInterface::kVeryHighBitrate,
608 video_options_.video_highest_bitrate.Set(
609 cricket::VideoOptions::VERY_HIGH);
610 } else if (FindConstraint(
612 MediaConstraintsInterface::kHighBitrate,
615 video_options_.video_highest_bitrate.Set(
616 cricket::VideoOptions::HIGH);
619 const cricket::VideoCodec default_codec(
620 JsepSessionDescription::kDefaultVideoCodecId,
621 JsepSessionDescription::kDefaultVideoCodecName,
622 JsepSessionDescription::kMaxVideoCodecWidth,
623 JsepSessionDescription::kMaxVideoCodecHeight,
624 JsepSessionDescription::kDefaultVideoCodecFramerate,
625 JsepSessionDescription::kDefaultVideoCodecPreference);
626 channel_manager_->SetDefaultVideoEncoderConfig(
627 cricket::VideoEncoderConfig(default_codec));
629 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
632 mediastream_signaling_,
633 dtls_identity_service,
639 webrtc_session_desc_factory_->SignalIdentityReady.connect(
640 this, &WebRtcSession::OnIdentityReady);
642 if (options.disable_encryption) {
643 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
649 void WebRtcSession::Terminate() {
650 SetState(STATE_RECEIVEDTERMINATE);
651 RemoveUnusedChannelsAndTransports(NULL);
652 ASSERT(voice_channel_.get() == NULL);
653 ASSERT(video_channel_.get() == NULL);
654 ASSERT(data_channel_.get() == NULL);
657 bool WebRtcSession::StartCandidatesAllocation() {
658 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
659 // from TransportProxy to start gathering ice candidates.
660 SpeculativelyConnectAllTransportChannels();
661 if (!saved_candidates_.empty()) {
662 // If there are saved candidates which arrived before local description is
663 // set, copy those to remote description.
664 CopySavedCandidates(remote_desc_.get());
666 // Push remote candidates present in remote description to transport channels.
667 UseCandidatesInSessionDescription(remote_desc_.get());
671 void WebRtcSession::SetSdesPolicy(cricket::SecurePolicy secure_policy) {
672 webrtc_session_desc_factory_->SetSdesPolicy(secure_policy);
675 cricket::SecurePolicy WebRtcSession::SdesPolicy() const {
676 return webrtc_session_desc_factory_->SdesPolicy();
679 bool WebRtcSession::GetSslRole(talk_base::SSLRole* role) {
680 if (local_description() == NULL || remote_description() == NULL) {
681 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
682 << "SSL Role of the session.";
686 // TODO(mallinath) - Return role of each transport, as role may differ from
688 // In current implementaion we just return the role of first transport in the
690 for (cricket::TransportMap::const_iterator iter = transport_proxies().begin();
691 iter != transport_proxies().end(); ++iter) {
692 if (iter->second->impl()) {
693 return iter->second->impl()->GetSslRole(role);
699 void WebRtcSession::CreateOffer(CreateSessionDescriptionObserver* observer,
700 const MediaConstraintsInterface* constraints) {
701 webrtc_session_desc_factory_->CreateOffer(observer, constraints);
704 void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
705 const MediaConstraintsInterface* constraints) {
706 webrtc_session_desc_factory_->CreateAnswer(observer, constraints);
709 bool WebRtcSession::SetLocalDescription(SessionDescriptionInterface* desc,
710 std::string* err_desc) {
711 // Takes the ownership of |desc| regardless of the result.
712 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
715 if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
719 // Update the initiator flag if this session is the initiator.
720 Action action = GetAction(desc->type());
721 if (state() == STATE_INIT && action == kOffer) {
725 cricket::SecurePolicy sdes_policy =
726 webrtc_session_desc_factory_->SdesPolicy();
727 cricket::CryptoType crypto_required = dtls_enabled_ ?
728 cricket::CT_DTLS : (sdes_policy == cricket::SEC_REQUIRED ?
729 cricket::CT_SDES : cricket::CT_NONE);
730 // Update the MediaContentDescription crypto settings as per the policy set.
731 UpdateSessionDescriptionSecurePolicy(crypto_required, desc->description());
733 set_local_description(desc->description()->Copy());
734 local_desc_.reset(desc_temp.release());
736 // Transport and Media channels will be created only when offer is set.
737 if (action == kOffer && !CreateChannels(local_desc_->description())) {
738 // TODO(mallinath) - Handle CreateChannel failure, as new local description
739 // is applied. Restore back to old description.
740 return BadLocalSdp(desc->type(), kCreateChannelFailed, err_desc);
743 // Remove channel and transport proxies, if MediaContentDescription is
745 RemoveUnusedChannelsAndTransports(local_desc_->description());
747 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
750 // Kick starting the ice candidates allocation.
751 StartCandidatesAllocation();
753 // Update state and SSRC of local MediaStreams and DataChannels based on the
754 // local session description.
755 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
757 talk_base::SSLRole role;
758 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
759 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
761 if (error() != cricket::BaseSession::ERROR_NONE) {
762 return BadLocalSdp(desc->type(), GetSessionErrorMsg(), err_desc);
767 bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
768 std::string* err_desc) {
769 // Takes the ownership of |desc| regardless of the result.
770 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
773 if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
777 // Transport and Media channels will be created only when offer is set.
778 Action action = GetAction(desc->type());
779 if (action == kOffer && !CreateChannels(desc->description())) {
780 // TODO(mallinath) - Handle CreateChannel failure, as new local description
781 // is applied. Restore back to old description.
782 return BadRemoteSdp(desc->type(), kCreateChannelFailed, err_desc);
785 // Remove channel and transport proxies, if MediaContentDescription is
787 RemoveUnusedChannelsAndTransports(desc->description());
789 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
791 set_remote_description(desc->description()->Copy());
792 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
796 // Update remote MediaStreams.
797 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
798 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
799 return BadRemoteSdp(desc->type(), kInvalidCandidates, err_desc);
802 // Copy all saved candidates.
803 CopySavedCandidates(desc);
804 // We retain all received candidates.
805 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
806 remote_desc_.get(), desc);
807 // Check if this new SessionDescription contains new ice ufrag and password
808 // that indicates the remote peer requests ice restart.
809 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(),
811 remote_desc_.reset(desc_temp.release());
813 talk_base::SSLRole role;
814 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
815 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
818 if (error() != cricket::BaseSession::ERROR_NONE) {
819 return BadRemoteSdp(desc->type(), GetSessionErrorMsg(), err_desc);
824 bool WebRtcSession::UpdateSessionState(
825 Action action, cricket::ContentSource source,
826 std::string* err_desc) {
827 // If there's already a pending error then no state transition should happen.
828 // But all call-sites should be verifying this before calling us!
829 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
831 if (action == kOffer) {
832 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
833 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
835 SetState(source == cricket::CS_LOCAL ?
836 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
837 if (error() != cricket::BaseSession::ERROR_NONE) {
838 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
840 } else if (action == kPrAnswer) {
841 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
842 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
845 SetState(source == cricket::CS_LOCAL ?
846 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
847 if (error() != cricket::BaseSession::ERROR_NONE) {
848 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
850 } else if (action == kAnswer) {
851 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
852 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
854 MaybeEnableMuxingSupport();
856 SetState(source == cricket::CS_LOCAL ?
857 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
858 if (error() != cricket::BaseSession::ERROR_NONE) {
859 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
865 WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
866 if (type == SessionDescriptionInterface::kOffer) {
867 return WebRtcSession::kOffer;
868 } else if (type == SessionDescriptionInterface::kPrAnswer) {
869 return WebRtcSession::kPrAnswer;
870 } else if (type == SessionDescriptionInterface::kAnswer) {
871 return WebRtcSession::kAnswer;
873 ASSERT(false && "unknown action type");
874 return WebRtcSession::kOffer;
877 bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
878 if (state() == STATE_INIT) {
879 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
880 << "without any offer (local or remote) "
881 << "session description.";
886 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
890 cricket::TransportProxy* transport_proxy = NULL;
891 if (remote_description()) {
892 size_t mediacontent_index =
893 static_cast<size_t>(candidate->sdp_mline_index());
894 size_t remote_content_size =
895 BaseSession::remote_description()->contents().size();
896 if (mediacontent_index >= remote_content_size) {
898 << "ProcessIceMessage: Invalid candidate media index.";
902 cricket::ContentInfo content =
903 BaseSession::remote_description()->contents()[mediacontent_index];
904 transport_proxy = GetTransportProxy(content.name);
907 // We need to check the local/remote description for the Transport instead of
908 // the session, because a new Transport added during renegotiation may have
909 // them unset while the session has them set from the previou negotiation. Not
910 // doing so may trigger the auto generation of transport description and mess
911 // up DTLS identity information, ICE credential, etc.
912 if (!transport_proxy || !(transport_proxy->local_description_set() &&
913 transport_proxy->remote_description_set())) {
914 LOG(LS_INFO) << "ProcessIceMessage: Local/Remote description not set "
915 << "on the Transport, save the candidate for later use.";
916 saved_candidates_.push_back(
917 new JsepIceCandidate(candidate->sdp_mid(), candidate->sdp_mline_index(),
918 candidate->candidate()));
922 // Add this candidate to the remote session description.
923 if (!remote_desc_->AddCandidate(candidate)) {
924 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
928 return UseCandidate(candidate);
931 bool WebRtcSession::UpdateIce(PeerConnectionInterface::IceTransportsType type) {
935 bool WebRtcSession::GetTrackIdBySsrc(uint32 ssrc, std::string* id) {
936 if (GetLocalTrackId(ssrc, id)) {
937 if (GetRemoteTrackId(ssrc, id)) {
938 LOG(LS_WARNING) << "SSRC " << ssrc
939 << " exists in both local and remote descriptions";
940 return true; // We return the remote track id.
944 return GetRemoteTrackId(ssrc, id);
948 bool WebRtcSession::GetLocalTrackId(uint32 ssrc, std::string* track_id) {
949 if (!BaseSession::local_description())
951 return webrtc::GetTrackIdBySsrc(
952 BaseSession::local_description(), ssrc, track_id);
955 bool WebRtcSession::GetRemoteTrackId(uint32 ssrc, std::string* track_id) {
956 if (!BaseSession::remote_description())
958 return webrtc::GetTrackIdBySsrc(
959 BaseSession::remote_description(), ssrc, track_id);
962 std::string WebRtcSession::BadStateErrMsg(State state) {
963 std::ostringstream desc;
964 desc << "Called in wrong state: " << GetStateString(state);
968 void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable,
969 cricket::AudioRenderer* renderer) {
970 ASSERT(signaling_thread()->IsCurrent());
971 if (!voice_channel_) {
972 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
975 if (!voice_channel_->SetRemoteRenderer(ssrc, renderer)) {
976 // SetRenderer() can fail if the ssrc does not match any playout channel.
977 LOG(LS_ERROR) << "SetAudioPlayout: ssrc is incorrect: " << ssrc;
980 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
981 // Allow that SetOutputScaling fail if |enable| is false but assert
982 // otherwise. This in the normal case when the underlying media channel has
983 // already been deleted.
984 ASSERT(enable == false);
988 void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
989 const cricket::AudioOptions& options,
990 cricket::AudioRenderer* renderer) {
991 ASSERT(signaling_thread()->IsCurrent());
992 if (!voice_channel_) {
993 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
996 if (!voice_channel_->SetLocalRenderer(ssrc, renderer)) {
997 // SetRenderer() can fail if the ssrc does not match any send channel.
998 LOG(LS_ERROR) << "SetAudioSend: ssrc is incorrect: " << ssrc;
1001 if (!voice_channel_->MuteStream(ssrc, !enable)) {
1002 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1003 // This in the normal case when the underlying media channel has already
1005 ASSERT(enable == false);
1009 voice_channel_->SetChannelOptions(options);
1012 void WebRtcSession::SetAudioPlayoutVolume(uint32 ssrc, double volume) {
1013 ASSERT(signaling_thread()->IsCurrent());
1014 ASSERT(volume >= 0 && volume <= 10);
1015 if (!voice_channel_) {
1016 LOG(LS_ERROR) << "SetAudioPlayoutVolume: No audio channel exists.";
1020 if (!voice_channel_->SetOutputScaling(ssrc, volume, volume))
1024 bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
1025 cricket::VideoCapturer* camera) {
1026 ASSERT(signaling_thread()->IsCurrent());
1028 if (!video_channel_.get()) {
1029 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
1031 LOG(LS_WARNING) << "Video not used in this call.";
1034 if (!video_channel_->SetCapturer(ssrc, camera)) {
1035 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
1036 // This in the normal case when the underlying media channel has already
1038 ASSERT(camera == NULL);
1044 void WebRtcSession::SetVideoPlayout(uint32 ssrc,
1046 cricket::VideoRenderer* renderer) {
1047 ASSERT(signaling_thread()->IsCurrent());
1048 if (!video_channel_) {
1049 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
1052 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
1053 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
1054 // This in the normal case when the underlying media channel has already
1056 ASSERT(renderer == NULL);
1060 void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
1061 const cricket::VideoOptions* options) {
1062 ASSERT(signaling_thread()->IsCurrent());
1063 if (!video_channel_) {
1064 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
1067 if (!video_channel_->MuteStream(ssrc, !enable)) {
1068 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1069 // This in the normal case when the underlying media channel has already
1071 ASSERT(enable == false);
1074 if (enable && options)
1075 video_channel_->SetChannelOptions(*options);
1078 bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
1079 ASSERT(signaling_thread()->IsCurrent());
1080 if (!voice_channel_) {
1081 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
1084 uint32 send_ssrc = 0;
1085 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
1087 if (!GetAudioSsrcByTrackId(BaseSession::local_description(), track_id,
1089 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1092 return voice_channel_->CanInsertDtmf();
1095 bool WebRtcSession::InsertDtmf(const std::string& track_id,
1096 int code, int duration) {
1097 ASSERT(signaling_thread()->IsCurrent());
1098 if (!voice_channel_) {
1099 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1102 uint32 send_ssrc = 0;
1103 if (!VERIFY(GetAudioSsrcByTrackId(BaseSession::local_description(),
1104 track_id, &send_ssrc))) {
1105 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1108 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1109 cricket::DF_SEND)) {
1110 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1116 sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1117 return &SignalVoiceChannelDestroyed;
1120 bool WebRtcSession::SendData(const cricket::SendDataParams& params,
1121 const talk_base::Buffer& payload,
1122 cricket::SendDataResult* result) {
1123 if (!data_channel_.get()) {
1124 LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
1127 return data_channel_->SendData(params, payload, result);
1130 bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
1131 if (!data_channel_.get()) {
1132 LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
1135 data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
1136 &DataChannel::OnChannelReady);
1137 data_channel_->SignalDataReceived.connect(webrtc_data_channel,
1138 &DataChannel::OnDataReceived);
1142 void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
1143 if (!data_channel_.get()) {
1144 LOG(LS_ERROR) << "DisconnectDataChannel called when data_channel_ is NULL.";
1147 data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
1148 data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
1151 void WebRtcSession::AddSctpDataStream(uint32 sid) {
1152 if (!data_channel_.get()) {
1153 LOG(LS_ERROR) << "AddDataChannelStreams called when data_channel_ is NULL.";
1156 data_channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(sid));
1157 data_channel_->AddSendStream(cricket::StreamParams::CreateLegacy(sid));
1160 void WebRtcSession::RemoveSctpDataStream(uint32 sid) {
1161 if (!data_channel_.get()) {
1162 LOG(LS_ERROR) << "RemoveDataChannelStreams called when data_channel_ is "
1166 data_channel_->RemoveRecvStream(sid);
1167 data_channel_->RemoveSendStream(sid);
1170 bool WebRtcSession::ReadyToSendData() const {
1171 return data_channel_.get() && data_channel_->ready_to_send_data();
1174 talk_base::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
1175 const std::string& label,
1176 const InternalDataChannelInit* config) {
1177 if (state() == STATE_RECEIVEDTERMINATE) {
1180 if (data_channel_type_ == cricket::DCT_NONE) {
1181 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1184 InternalDataChannelInit new_config =
1185 config ? (*config) : InternalDataChannelInit();
1186 if (data_channel_type_ == cricket::DCT_SCTP) {
1187 if (new_config.id < 0) {
1188 talk_base::SSLRole role;
1189 if (GetSslRole(&role) &&
1190 !mediastream_signaling_->AllocateSctpSid(role, &new_config.id)) {
1191 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1194 } else if (!mediastream_signaling_->IsSctpSidAvailable(new_config.id)) {
1195 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1196 << "because the id is already in use or out of range.";
1201 talk_base::scoped_refptr<DataChannel> channel(DataChannel::Create(
1202 this, data_channel_type_, label, new_config));
1203 if (channel && !mediastream_signaling_->AddDataChannel(channel))
1209 cricket::DataChannelType WebRtcSession::data_channel_type() const {
1210 return data_channel_type_;
1213 bool WebRtcSession::IceRestartPending() const {
1214 return ice_restart_latch_->Get();
1217 void WebRtcSession::ResetIceRestartLatch() {
1218 ice_restart_latch_->Reset();
1221 void WebRtcSession::OnIdentityReady(talk_base::SSLIdentity* identity) {
1222 SetIdentity(identity);
1225 bool WebRtcSession::waiting_for_identity() const {
1226 return webrtc_session_desc_factory_->waiting_for_identity();
1229 void WebRtcSession::SetIceConnectionState(
1230 PeerConnectionInterface::IceConnectionState state) {
1231 if (ice_connection_state_ == state) {
1235 // ASSERT that the requested transition is allowed. Note that
1236 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1237 // within PeerConnection). This switch statement should compile away when
1238 // ASSERTs are disabled.
1239 switch (ice_connection_state_) {
1240 case PeerConnectionInterface::kIceConnectionNew:
1241 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1243 case PeerConnectionInterface::kIceConnectionChecking:
1244 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1245 state == PeerConnectionInterface::kIceConnectionConnected);
1247 case PeerConnectionInterface::kIceConnectionConnected:
1248 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1249 state == PeerConnectionInterface::kIceConnectionChecking ||
1250 state == PeerConnectionInterface::kIceConnectionCompleted);
1252 case PeerConnectionInterface::kIceConnectionCompleted:
1253 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1254 state == PeerConnectionInterface::kIceConnectionDisconnected);
1256 case PeerConnectionInterface::kIceConnectionFailed:
1257 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1259 case PeerConnectionInterface::kIceConnectionDisconnected:
1260 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1261 state == PeerConnectionInterface::kIceConnectionConnected ||
1262 state == PeerConnectionInterface::kIceConnectionCompleted ||
1263 state == PeerConnectionInterface::kIceConnectionFailed);
1265 case PeerConnectionInterface::kIceConnectionClosed:
1273 ice_connection_state_ = state;
1274 if (ice_observer_) {
1275 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1279 void WebRtcSession::OnTransportRequestSignaling(
1280 cricket::Transport* transport) {
1281 ASSERT(signaling_thread()->IsCurrent());
1282 transport->OnSignalingReady();
1283 if (ice_observer_) {
1284 ice_observer_->OnIceGatheringChange(
1285 PeerConnectionInterface::kIceGatheringGathering);
1289 void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1290 ASSERT(signaling_thread()->IsCurrent());
1291 // start monitoring for the write state of the transport.
1292 OnTransportWritable(transport);
1295 void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1296 ASSERT(signaling_thread()->IsCurrent());
1297 if (transport->all_channels_writable()) {
1298 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
1299 } else if (transport->HasChannels()) {
1300 // If the current state is Connected or Completed, then there were writable
1301 // channels but now there are not, so the next state must be Disconnected.
1302 if (ice_connection_state_ ==
1303 PeerConnectionInterface::kIceConnectionConnected ||
1304 ice_connection_state_ ==
1305 PeerConnectionInterface::kIceConnectionCompleted) {
1306 SetIceConnectionState(
1307 PeerConnectionInterface::kIceConnectionDisconnected);
1312 void WebRtcSession::OnTransportCompleted(cricket::Transport* transport) {
1313 ASSERT(signaling_thread()->IsCurrent());
1314 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
1317 void WebRtcSession::OnTransportFailed(cricket::Transport* transport) {
1318 ASSERT(signaling_thread()->IsCurrent());
1319 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
1322 void WebRtcSession::OnTransportProxyCandidatesReady(
1323 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1324 ASSERT(signaling_thread()->IsCurrent());
1325 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1328 void WebRtcSession::OnCandidatesAllocationDone() {
1329 ASSERT(signaling_thread()->IsCurrent());
1330 if (ice_observer_) {
1331 ice_observer_->OnIceGatheringChange(
1332 PeerConnectionInterface::kIceGatheringComplete);
1333 ice_observer_->OnIceComplete();
1337 // Enabling voice and video channel.
1338 void WebRtcSession::EnableChannels() {
1339 if (voice_channel_ && !voice_channel_->enabled())
1340 voice_channel_->Enable(true);
1342 if (video_channel_ && !video_channel_->enabled())
1343 video_channel_->Enable(true);
1345 if (data_channel_.get() && !data_channel_->enabled())
1346 data_channel_->Enable(true);
1349 void WebRtcSession::ProcessNewLocalCandidate(
1350 const std::string& content_name,
1351 const cricket::Candidates& candidates) {
1352 int sdp_mline_index;
1353 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1354 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1355 << content_name << " not found";
1359 for (cricket::Candidates::const_iterator citer = candidates.begin();
1360 citer != candidates.end(); ++citer) {
1361 // Use content_name as the candidate media id.
1362 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1363 if (ice_observer_) {
1364 ice_observer_->OnIceCandidate(&candidate);
1367 local_desc_->AddCandidate(&candidate);
1372 // Returns the media index for a local ice candidate given the content name.
1373 bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1374 int* sdp_mline_index) {
1375 if (!BaseSession::local_description() || !sdp_mline_index)
1378 bool content_found = false;
1379 const ContentInfos& contents = BaseSession::local_description()->contents();
1380 for (size_t index = 0; index < contents.size(); ++index) {
1381 if (contents[index].name == content_name) {
1382 *sdp_mline_index = static_cast<int>(index);
1383 content_found = true;
1387 return content_found;
1390 bool WebRtcSession::UseCandidatesInSessionDescription(
1391 const SessionDescriptionInterface* remote_desc) {
1395 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1396 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1397 for (size_t n = 0; n < candidates->count(); ++n) {
1398 ret = UseCandidate(candidates->at(n));
1406 bool WebRtcSession::UseCandidate(
1407 const IceCandidateInterface* candidate) {
1409 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
1410 size_t remote_content_size =
1411 BaseSession::remote_description()->contents().size();
1412 if (mediacontent_index >= remote_content_size) {
1414 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1418 cricket::ContentInfo content =
1419 BaseSession::remote_description()->contents()[mediacontent_index];
1420 std::vector<cricket::Candidate> candidates;
1421 candidates.push_back(candidate->candidate());
1422 // Invoking BaseSession method to handle remote candidates.
1424 if (OnRemoteCandidates(content.name, candidates, &error)) {
1425 // Candidates successfully submitted for checking.
1426 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1427 ice_connection_state_ ==
1428 PeerConnectionInterface::kIceConnectionDisconnected) {
1429 // If state is New, then the session has just gotten its first remote ICE
1430 // candidates, so go to Checking.
1431 // If state is Disconnected, the session is re-using old candidates or
1432 // receiving additional ones, so go to Checking.
1433 // If state is Connected, stay Connected.
1434 // TODO(bemasc): If state is Connected, and the new candidates are for a
1435 // newly added transport, then the state actually _should_ move to
1436 // checking. Add a way to distinguish that case.
1437 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1439 // TODO(bemasc): If state is Completed, go back to Connected.
1441 if (!error.empty()) {
1442 LOG(LS_WARNING) << error;
1448 void WebRtcSession::RemoveUnusedChannelsAndTransports(
1449 const SessionDescription* desc) {
1450 const cricket::ContentInfo* voice_info =
1451 cricket::GetFirstAudioContent(desc);
1452 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1453 mediastream_signaling_->OnAudioChannelClose();
1454 SignalVoiceChannelDestroyed();
1455 const std::string content_name = voice_channel_->content_name();
1456 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
1457 DestroyTransportProxy(content_name);
1460 const cricket::ContentInfo* video_info =
1461 cricket::GetFirstVideoContent(desc);
1462 if ((!video_info || video_info->rejected) && video_channel_) {
1463 mediastream_signaling_->OnVideoChannelClose();
1464 SignalVideoChannelDestroyed();
1465 const std::string content_name = video_channel_->content_name();
1466 channel_manager_->DestroyVideoChannel(video_channel_.release());
1467 DestroyTransportProxy(content_name);
1470 const cricket::ContentInfo* data_info =
1471 cricket::GetFirstDataContent(desc);
1472 if ((!data_info || data_info->rejected) && data_channel_) {
1473 mediastream_signaling_->OnDataChannelClose();
1474 SignalDataChannelDestroyed();
1475 const std::string content_name = data_channel_->content_name();
1476 channel_manager_->DestroyDataChannel(data_channel_.release());
1477 DestroyTransportProxy(content_name);
1481 // TODO(mallinath) - Add a correct error code if the channels are not creatued
1482 // due to BUNDLE is enabled but rtcp-mux is disabled.
1483 bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
1484 // Disabling the BUNDLE flag in PortAllocator if offer disabled it.
1485 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1486 if (state() == STATE_INIT && !bundle_enabled) {
1487 port_allocator()->set_flags(port_allocator()->flags() &
1488 ~cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1491 // Creating the media channels and transport proxies.
1492 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1493 if (voice && !voice->rejected && !voice_channel_) {
1494 if (!CreateVoiceChannel(voice)) {
1495 LOG(LS_ERROR) << "Failed to create voice channel.";
1500 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1501 if (video && !video->rejected && !video_channel_) {
1502 if (!CreateVideoChannel(video)) {
1503 LOG(LS_ERROR) << "Failed to create video channel.";
1508 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1509 if (data_channel_type_ != cricket::DCT_NONE &&
1510 data && !data->rejected && !data_channel_.get()) {
1511 if (!CreateDataChannel(data)) {
1512 LOG(LS_ERROR) << "Failed to create data channel.";
1520 bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
1521 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
1522 this, content->name, true));
1523 if (!voice_channel_.get())
1526 voice_channel_->SetChannelOptions(audio_options_);
1530 bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
1531 video_channel_.reset(channel_manager_->CreateVideoChannel(
1532 this, content->name, true, voice_channel_.get()));
1533 if (!video_channel_.get())
1536 video_channel_->SetChannelOptions(video_options_);
1540 bool WebRtcSession::CreateDataChannel(const cricket::ContentInfo* content) {
1541 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
1542 data_channel_.reset(channel_manager_->CreateDataChannel(
1543 this, content->name, !sctp, data_channel_type_));
1544 if (!data_channel_.get()) {
1548 mediastream_signaling_->OnDataTransportCreatedForSctp();
1549 data_channel_->SignalDataReceived.connect(
1550 this, &WebRtcSession::OnDataChannelMessageReceived);
1555 void WebRtcSession::CopySavedCandidates(
1556 SessionDescriptionInterface* dest_desc) {
1561 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1562 dest_desc->AddCandidate(saved_candidates_[i]);
1563 delete saved_candidates_[i];
1565 saved_candidates_.clear();
1568 void WebRtcSession::OnDataChannelMessageReceived(
1569 cricket::DataChannel* channel,
1570 const cricket::ReceiveDataParams& params,
1571 const talk_base::Buffer& payload) {
1572 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
1573 if (params.type == cricket::DMT_CONTROL &&
1574 mediastream_signaling_->IsSctpSidAvailable(params.ssrc)) {
1575 // Received CONTROL on unused sid, process as an OPEN message.
1576 mediastream_signaling_->AddDataChannelFromOpenMessage(params, payload);
1578 // otherwise ignore the message.
1581 // Returns false if bundle is enabled and rtcp_mux is disabled.
1582 bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
1583 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1584 if (!bundle_enabled)
1587 const cricket::ContentGroup* bundle_group =
1588 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1589 ASSERT(bundle_group != NULL);
1591 const cricket::ContentInfos& contents = desc->contents();
1592 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1593 citer != contents.end(); ++citer) {
1594 const cricket::ContentInfo* content = (&*citer);
1595 ASSERT(content != NULL);
1596 if (bundle_group->HasContentName(content->name) &&
1597 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1598 if (!HasRtcpMuxEnabled(content))
1602 // RTCP-MUX is enabled in all the contents.
1606 bool WebRtcSession::HasRtcpMuxEnabled(
1607 const cricket::ContentInfo* content) {
1608 const cricket::MediaContentDescription* description =
1609 static_cast<cricket::MediaContentDescription*>(content->description);
1610 return description->rtcp_mux();
1613 bool WebRtcSession::ValidateSessionDescription(
1614 const SessionDescriptionInterface* sdesc,
1615 cricket::ContentSource source, std::string* err_desc) {
1617 if (error() != cricket::BaseSession::ERROR_NONE) {
1618 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
1621 if (!sdesc || !sdesc->description()) {
1622 return BadSdp(source, type, kInvalidSdp, err_desc);
1625 type = sdesc->type();
1626 Action action = GetAction(sdesc->type());
1627 if (source == cricket::CS_LOCAL) {
1628 if (!ExpectSetLocalDescription(action))
1629 return BadLocalSdp(type, BadStateErrMsg(state()), err_desc);
1631 if (!ExpectSetRemoteDescription(action))
1632 return BadRemoteSdp(type, BadStateErrMsg(state()), err_desc);
1635 // Verify crypto settings.
1636 std::string crypto_error;
1637 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
1639 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
1640 return BadSdp(source, type, crypto_error, err_desc);
1643 // Verify ice-ufrag and ice-pwd.
1644 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
1645 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
1648 if (!ValidateBundleSettings(sdesc->description())) {
1649 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
1652 // Verify m-lines in Answer when compared against Offer.
1653 if (action == kAnswer) {
1654 const cricket::SessionDescription* offer_desc =
1655 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1656 local_description()->description();
1657 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
1658 return BadAnswerSdp(source, kMlineMismatch, err_desc);
1665 bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1666 return ((action == kOffer && state() == STATE_INIT) ||
1667 // update local offer
1668 (action == kOffer && state() == STATE_SENTINITIATE) ||
1669 // update the current ongoing session.
1670 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1671 (action == kOffer && state() == STATE_SENTACCEPT) ||
1672 (action == kOffer && state() == STATE_INPROGRESS) ||
1673 // accept remote offer
1674 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1675 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1676 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1677 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1680 bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1681 return ((action == kOffer && state() == STATE_INIT) ||
1682 // update remote offer
1683 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1684 // update the current ongoing session
1685 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1686 (action == kOffer && state() == STATE_SENTACCEPT) ||
1687 (action == kOffer && state() == STATE_INPROGRESS) ||
1688 // accept local offer
1689 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1690 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1691 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1692 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1695 std::string WebRtcSession::GetSessionErrorMsg() {
1696 std::ostringstream desc;
1697 desc << kSessionError << GetErrorCodeString(error()) << ". ";
1698 desc << kSessionErrorDesc << error_desc() << ".";
1702 } // namespace webrtc