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/media/base/constants.h"
42 #include "talk/media/base/videocapturer.h"
43 #include "talk/session/media/channel.h"
44 #include "talk/session/media/channelmanager.h"
45 #include "talk/session/media/mediasession.h"
46 #include "webrtc/base/basictypes.h"
47 #include "webrtc/base/helpers.h"
48 #include "webrtc/base/logging.h"
49 #include "webrtc/base/stringencode.h"
50 #include "webrtc/base/stringutils.h"
52 using cricket::ContentInfo;
53 using cricket::ContentInfos;
54 using cricket::MediaContentDescription;
55 using cricket::SessionDescription;
56 using cricket::TransportInfo;
61 const char kBundleWithoutRtcpMux[] = "RTCP-MUX must be enabled when BUNDLE "
63 const char kCreateChannelFailed[] = "Failed to create channels.";
64 const char kInvalidCandidates[] = "Description contains invalid candidates.";
65 const char kInvalidSdp[] = "Invalid session description.";
66 const char kMlineMismatch[] =
67 "Offer and answer descriptions m-lines are not matching. Rejecting answer.";
68 const char kPushDownTDFailed[] =
69 "Failed to push down transport description:";
70 const char kSdpWithoutDtlsFingerprint[] =
71 "Called with SDP without DTLS fingerprint.";
72 const char kSdpWithoutSdesCrypto[] =
73 "Called with SDP without SDES crypto.";
74 const char kSdpWithoutIceUfragPwd[] =
75 "Called with SDP without ice-ufrag and ice-pwd.";
76 const char kSessionError[] = "Session error code: ";
77 const char kSessionErrorDesc[] = "Session error description: ";
78 const int kMaxUnsignalledRecvStreams = 20;
80 // Compares |answer| against |offer|. Comparision is done
81 // for number of m-lines in answer against offer. If matches true will be
82 // returned otherwise false.
83 static bool VerifyMediaDescriptions(
84 const SessionDescription* answer, const SessionDescription* offer) {
85 if (offer->contents().size() != answer->contents().size())
88 for (size_t i = 0; i < offer->contents().size(); ++i) {
89 if ((offer->contents()[i].name) != answer->contents()[i].name) {
92 const MediaContentDescription* offer_mdesc =
93 static_cast<const MediaContentDescription*>(
94 offer->contents()[i].description);
95 const MediaContentDescription* answer_mdesc =
96 static_cast<const MediaContentDescription*>(
97 answer->contents()[i].description);
98 if (offer_mdesc->type() != answer_mdesc->type()) {
105 // Checks that each non-rejected content has SDES crypto keys or a DTLS
106 // fingerprint. Mismatches, such as replying with a DTLS fingerprint to SDES
107 // keys, will be caught in Transport negotiation, and backstopped by Channel's
108 // |secure_required| check.
109 static bool VerifyCrypto(const SessionDescription* desc,
111 std::string* error) {
112 const ContentInfos& contents = desc->contents();
113 for (size_t index = 0; index < contents.size(); ++index) {
114 const ContentInfo* cinfo = &contents[index];
115 if (cinfo->rejected) {
119 // If the content isn't rejected, crypto must be present.
120 const MediaContentDescription* media =
121 static_cast<const MediaContentDescription*>(cinfo->description);
122 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
123 if (!media || !tinfo) {
124 // Something is not right.
125 LOG(LS_ERROR) << kInvalidSdp;
126 *error = kInvalidSdp;
130 if (!tinfo->description.identity_fingerprint) {
132 "Session description must have DTLS fingerprint if DTLS enabled.";
133 *error = kSdpWithoutDtlsFingerprint;
137 if (media->cryptos().empty()) {
139 "Session description must have SDES when DTLS disabled.";
140 *error = kSdpWithoutSdesCrypto;
149 // Checks that each non-rejected content has ice-ufrag and ice-pwd set.
150 static bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
151 const ContentInfos& contents = desc->contents();
152 for (size_t index = 0; index < contents.size(); ++index) {
153 const ContentInfo* cinfo = &contents[index];
154 if (cinfo->rejected) {
158 // If the content isn't rejected, ice-ufrag and ice-pwd must be present.
159 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
161 // Something is not right.
162 LOG(LS_ERROR) << kInvalidSdp;
165 if (tinfo->description.ice_ufrag.empty() ||
166 tinfo->description.ice_pwd.empty()) {
167 LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
174 // Forces |sdesc->crypto_required| to the appropriate state based on the
175 // current security policy, to ensure a failure occurs if there is an error
176 // in crypto negotiation.
177 // Called when processing the local session description.
178 static void UpdateSessionDescriptionSecurePolicy(cricket::CryptoType type,
179 SessionDescription* sdesc) {
184 // Updating the |crypto_required_| in MediaContentDescription to the
185 // appropriate state based on the current security policy.
186 for (cricket::ContentInfos::iterator iter = sdesc->contents().begin();
187 iter != sdesc->contents().end(); ++iter) {
188 if (cricket::IsMediaContent(&*iter)) {
189 MediaContentDescription* mdesc =
190 static_cast<MediaContentDescription*> (iter->description);
192 mdesc->set_crypto_required(type);
198 static bool GetAudioSsrcByTrackId(
199 const SessionDescription* session_description,
200 const std::string& track_id, uint32 *ssrc) {
201 const cricket::ContentInfo* audio_info =
202 cricket::GetFirstAudioContent(session_description);
204 LOG(LS_ERROR) << "Audio not used in this call";
208 const cricket::MediaContentDescription* audio_content =
209 static_cast<const cricket::MediaContentDescription*>(
210 audio_info->description);
211 cricket::StreamParams stream;
212 if (!cricket::GetStreamByIds(audio_content->streams(), "", track_id,
216 *ssrc = stream.first_ssrc();
220 static bool GetTrackIdBySsrc(const SessionDescription* session_description,
221 uint32 ssrc, std::string* track_id) {
222 ASSERT(track_id != NULL);
224 cricket::StreamParams stream_out;
225 const cricket::ContentInfo* audio_info =
226 cricket::GetFirstAudioContent(session_description);
230 const cricket::MediaContentDescription* audio_content =
231 static_cast<const cricket::MediaContentDescription*>(
232 audio_info->description);
234 if (cricket::GetStreamBySsrc(audio_content->streams(), ssrc, &stream_out)) {
235 *track_id = stream_out.id;
239 const cricket::ContentInfo* video_info =
240 cricket::GetFirstVideoContent(session_description);
244 const cricket::MediaContentDescription* video_content =
245 static_cast<const cricket::MediaContentDescription*>(
246 video_info->description);
248 if (cricket::GetStreamBySsrc(video_content->streams(), ssrc, &stream_out)) {
249 *track_id = stream_out.id;
255 static bool BadSdp(const std::string& source,
256 const std::string& type,
257 const std::string& reason,
258 std::string* err_desc) {
259 std::ostringstream desc;
260 desc << "Failed to set " << source << " " << type << " sdp: " << reason;
263 *err_desc = desc.str();
265 LOG(LS_ERROR) << desc.str();
269 static bool BadSdp(cricket::ContentSource source,
270 const std::string& type,
271 const std::string& reason,
272 std::string* err_desc) {
273 if (source == cricket::CS_LOCAL) {
274 return BadSdp("local", type, reason, err_desc);
276 return BadSdp("remote", type, reason, err_desc);
280 static bool BadLocalSdp(const std::string& type,
281 const std::string& reason,
282 std::string* err_desc) {
283 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
286 static bool BadRemoteSdp(const std::string& type,
287 const std::string& reason,
288 std::string* err_desc) {
289 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
292 static bool BadOfferSdp(cricket::ContentSource source,
293 const std::string& reason,
294 std::string* err_desc) {
295 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
298 static bool BadPranswerSdp(cricket::ContentSource source,
299 const std::string& reason,
300 std::string* err_desc) {
301 return BadSdp(source, SessionDescriptionInterface::kPrAnswer,
305 static bool BadAnswerSdp(cricket::ContentSource source,
306 const std::string& reason,
307 std::string* err_desc) {
308 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
311 #define GET_STRING_OF_STATE(state) \
312 case cricket::BaseSession::state: \
316 static std::string GetStateString(cricket::BaseSession::State state) {
319 GET_STRING_OF_STATE(STATE_INIT)
320 GET_STRING_OF_STATE(STATE_SENTINITIATE)
321 GET_STRING_OF_STATE(STATE_RECEIVEDINITIATE)
322 GET_STRING_OF_STATE(STATE_SENTPRACCEPT)
323 GET_STRING_OF_STATE(STATE_SENTACCEPT)
324 GET_STRING_OF_STATE(STATE_RECEIVEDPRACCEPT)
325 GET_STRING_OF_STATE(STATE_RECEIVEDACCEPT)
326 GET_STRING_OF_STATE(STATE_SENTMODIFY)
327 GET_STRING_OF_STATE(STATE_RECEIVEDMODIFY)
328 GET_STRING_OF_STATE(STATE_SENTREJECT)
329 GET_STRING_OF_STATE(STATE_RECEIVEDREJECT)
330 GET_STRING_OF_STATE(STATE_SENTREDIRECT)
331 GET_STRING_OF_STATE(STATE_SENTTERMINATE)
332 GET_STRING_OF_STATE(STATE_RECEIVEDTERMINATE)
333 GET_STRING_OF_STATE(STATE_INPROGRESS)
334 GET_STRING_OF_STATE(STATE_DEINIT)
342 #define GET_STRING_OF_ERROR_CODE(err) \
343 case cricket::BaseSession::err: \
347 static std::string GetErrorCodeString(cricket::BaseSession::Error err) {
350 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
351 GET_STRING_OF_ERROR_CODE(ERROR_TIME)
352 GET_STRING_OF_ERROR_CODE(ERROR_RESPONSE)
353 GET_STRING_OF_ERROR_CODE(ERROR_NETWORK)
354 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
355 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
363 static std::string MakeErrorString(const std::string& error,
364 const std::string& desc) {
365 std::ostringstream ret;
366 ret << error << " " << desc;
370 static std::string MakeTdErrorString(const std::string& desc) {
371 return MakeErrorString(kPushDownTDFailed, desc);
374 // Set |option| to the highest-priority value of |key| in the optional
375 // constraints if the key is found and has a valid value.
377 static void SetOptionFromOptionalConstraint(
378 const MediaConstraintsInterface* constraints,
379 const std::string& key, cricket::Settable<T>* option) {
383 std::string string_value;
385 if (constraints->GetOptional().FindFirst(key, &string_value)) {
386 if (rtc::FromString(string_value, &value)) {
392 // Help class used to remember if a a remote peer has requested ice restart by
393 // by sending a description with new ice ufrag and password.
394 class IceRestartAnswerLatch {
396 IceRestartAnswerLatch() : ice_restart_(false) { }
398 // Returns true if CheckForRemoteIceRestart has been called with a new session
399 // description where ice password and ufrag has changed since last time
400 // Reset() was called.
407 ice_restart_ = false;
411 void CheckForRemoteIceRestart(
412 const SessionDescriptionInterface* old_desc,
413 const SessionDescriptionInterface* new_desc) {
414 if (!old_desc || new_desc->type() != SessionDescriptionInterface::kOffer) {
417 const SessionDescription* new_sd = new_desc->description();
418 const SessionDescription* old_sd = old_desc->description();
419 const ContentInfos& contents = new_sd->contents();
420 for (size_t index = 0; index < contents.size(); ++index) {
421 const ContentInfo* cinfo = &contents[index];
422 if (cinfo->rejected) {
425 // If the content isn't rejected, check if ufrag and password has
427 const cricket::TransportDescription* new_transport_desc =
428 new_sd->GetTransportDescriptionByName(cinfo->name);
429 const cricket::TransportDescription* old_transport_desc =
430 old_sd->GetTransportDescriptionByName(cinfo->name);
431 if (!new_transport_desc || !old_transport_desc) {
432 // No transport description exist. This is not an ice restart.
435 if (cricket::IceCredentialsChanged(old_transport_desc->ice_ufrag,
436 old_transport_desc->ice_pwd,
437 new_transport_desc->ice_ufrag,
438 new_transport_desc->ice_pwd)) {
439 LOG(LS_INFO) << "Remote peer request ice restart.";
450 WebRtcSession::WebRtcSession(
451 cricket::ChannelManager* channel_manager,
452 rtc::Thread* signaling_thread,
453 rtc::Thread* worker_thread,
454 cricket::PortAllocator* port_allocator,
455 MediaStreamSignaling* mediastream_signaling)
456 : cricket::BaseSession(signaling_thread, worker_thread, port_allocator,
457 rtc::ToString(rtc::CreateRandomId64() &
459 cricket::NS_JINGLE_RTP, false),
460 // RFC 3264: The numeric value of the session id and version in the
461 // o line MUST be representable with a "64 bit signed integer".
462 // Due to this constraint session id |sid_| is max limited to LLONG_MAX.
463 channel_manager_(channel_manager),
464 mediastream_signaling_(mediastream_signaling),
466 ice_connection_state_(PeerConnectionInterface::kIceConnectionNew),
467 older_version_remote_peer_(false),
468 dtls_enabled_(false),
469 data_channel_type_(cricket::DCT_NONE),
470 ice_restart_latch_(new IceRestartAnswerLatch) {
473 WebRtcSession::~WebRtcSession() {
474 if (voice_channel_.get()) {
475 SignalVoiceChannelDestroyed();
476 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
478 if (video_channel_.get()) {
479 SignalVideoChannelDestroyed();
480 channel_manager_->DestroyVideoChannel(video_channel_.release());
482 if (data_channel_.get()) {
483 SignalDataChannelDestroyed();
484 channel_manager_->DestroyDataChannel(data_channel_.release());
486 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
487 delete saved_candidates_[i];
492 bool WebRtcSession::Initialize(
493 const PeerConnectionFactoryInterface::Options& options,
494 const MediaConstraintsInterface* constraints,
495 DTLSIdentityServiceInterface* dtls_identity_service,
496 PeerConnectionInterface::IceTransportsType ice_transport) {
497 // TODO(perkj): Take |constraints| into consideration. Return false if not all
498 // mandatory constraints can be fulfilled. Note that |constraints|
502 if (options.disable_encryption) {
503 dtls_enabled_ = false;
505 // Enable DTLS by default if |dtls_identity_service| is valid.
506 dtls_enabled_ = (dtls_identity_service != NULL);
507 // |constraints| can override the default |dtls_enabled_| value.
510 MediaConstraintsInterface::kEnableDtlsSrtp,
512 dtls_enabled_ = value;
516 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
517 // It takes precendence over the disable_sctp_data_channels
518 // PeerConnectionFactoryInterface::Options.
520 constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
521 &value, NULL) && value) {
522 LOG(LS_INFO) << "Allowing RTP data engine.";
523 data_channel_type_ = cricket::DCT_RTP;
525 // DTLS has to be enabled to use SCTP.
526 if (!options.disable_sctp_data_channels && dtls_enabled_) {
527 LOG(LS_INFO) << "Allowing SCTP data engine.";
528 data_channel_type_ = cricket::DCT_SCTP;
531 if (data_channel_type_ != cricket::DCT_NONE) {
532 mediastream_signaling_->SetDataChannelFactory(this);
535 // Find DSCP constraint.
538 MediaConstraintsInterface::kEnableDscp,
540 audio_options_.dscp.Set(value);
541 video_options_.dscp.Set(value);
544 // Find Suspend Below Min Bitrate constraint.
547 MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate,
550 video_options_.suspend_below_min_bitrate.Set(value);
553 SetOptionFromOptionalConstraint(constraints,
554 MediaConstraintsInterface::kScreencastMinBitrate,
555 &video_options_.screencast_min_bitrate);
557 // Find constraints for cpu overuse detection.
558 SetOptionFromOptionalConstraint(constraints,
559 MediaConstraintsInterface::kCpuUnderuseThreshold,
560 &video_options_.cpu_underuse_threshold);
561 SetOptionFromOptionalConstraint(constraints,
562 MediaConstraintsInterface::kCpuOveruseThreshold,
563 &video_options_.cpu_overuse_threshold);
564 SetOptionFromOptionalConstraint(constraints,
565 MediaConstraintsInterface::kCpuOveruseDetection,
566 &video_options_.cpu_overuse_detection);
567 SetOptionFromOptionalConstraint(constraints,
568 MediaConstraintsInterface::kCpuOveruseEncodeUsage,
569 &video_options_.cpu_overuse_encode_usage);
570 SetOptionFromOptionalConstraint(constraints,
571 MediaConstraintsInterface::kCpuUnderuseEncodeRsdThreshold,
572 &video_options_.cpu_underuse_encode_rsd_threshold);
573 SetOptionFromOptionalConstraint(constraints,
574 MediaConstraintsInterface::kCpuOveruseEncodeRsdThreshold,
575 &video_options_.cpu_overuse_encode_rsd_threshold);
577 // Find payload padding constraint.
578 SetOptionFromOptionalConstraint(constraints,
579 MediaConstraintsInterface::kPayloadPadding,
580 &video_options_.use_payload_padding);
582 // Find improved wifi bwe constraint.
585 MediaConstraintsInterface::kImprovedWifiBwe,
588 video_options_.use_improved_wifi_bandwidth_estimator.Set(value);
590 // Enable by default if the constraint is not set.
591 video_options_.use_improved_wifi_bandwidth_estimator.Set(true);
594 SetOptionFromOptionalConstraint(constraints,
595 MediaConstraintsInterface::kNumUnsignalledRecvStreams,
596 &video_options_.unsignalled_recv_stream_limit);
597 if (video_options_.unsignalled_recv_stream_limit.IsSet()) {
599 video_options_.unsignalled_recv_stream_limit.Get(&stream_limit);
600 stream_limit = rtc::_min(kMaxUnsignalledRecvStreams, stream_limit);
601 stream_limit = rtc::_max(0, stream_limit);
602 video_options_.unsignalled_recv_stream_limit.Set(stream_limit);
605 SetOptionFromOptionalConstraint(constraints,
606 MediaConstraintsInterface::kHighStartBitrate,
607 &video_options_.video_start_bitrate);
611 MediaConstraintsInterface::kVeryHighBitrate,
614 video_options_.video_highest_bitrate.Set(
615 cricket::VideoOptions::VERY_HIGH);
616 } else if (FindConstraint(
618 MediaConstraintsInterface::kHighBitrate,
621 video_options_.video_highest_bitrate.Set(
622 cricket::VideoOptions::HIGH);
625 SetOptionFromOptionalConstraint(constraints,
626 MediaConstraintsInterface::kOpusFec,
627 &audio_options_.opus_fec);
629 const cricket::VideoCodec default_codec(
630 JsepSessionDescription::kDefaultVideoCodecId,
631 JsepSessionDescription::kDefaultVideoCodecName,
632 JsepSessionDescription::kMaxVideoCodecWidth,
633 JsepSessionDescription::kMaxVideoCodecHeight,
634 JsepSessionDescription::kDefaultVideoCodecFramerate,
635 JsepSessionDescription::kDefaultVideoCodecPreference);
636 channel_manager_->SetDefaultVideoEncoderConfig(
637 cricket::VideoEncoderConfig(default_codec));
639 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
642 mediastream_signaling_,
643 dtls_identity_service,
649 webrtc_session_desc_factory_->SignalIdentityReady.connect(
650 this, &WebRtcSession::OnIdentityReady);
652 if (options.disable_encryption) {
653 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
659 void WebRtcSession::Terminate() {
660 SetState(STATE_RECEIVEDTERMINATE);
661 RemoveUnusedChannelsAndTransports(NULL);
662 ASSERT(voice_channel_.get() == NULL);
663 ASSERT(video_channel_.get() == NULL);
664 ASSERT(data_channel_.get() == NULL);
667 bool WebRtcSession::StartCandidatesAllocation() {
668 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
669 // from TransportProxy to start gathering ice candidates.
670 SpeculativelyConnectAllTransportChannels();
671 if (!saved_candidates_.empty()) {
672 // If there are saved candidates which arrived before local description is
673 // set, copy those to remote description.
674 CopySavedCandidates(remote_desc_.get());
676 // Push remote candidates present in remote description to transport channels.
677 UseCandidatesInSessionDescription(remote_desc_.get());
681 void WebRtcSession::SetSdesPolicy(cricket::SecurePolicy secure_policy) {
682 webrtc_session_desc_factory_->SetSdesPolicy(secure_policy);
685 cricket::SecurePolicy WebRtcSession::SdesPolicy() const {
686 return webrtc_session_desc_factory_->SdesPolicy();
689 bool WebRtcSession::GetSslRole(rtc::SSLRole* role) {
690 if (local_description() == NULL || remote_description() == NULL) {
691 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
692 << "SSL Role of the session.";
696 // TODO(mallinath) - Return role of each transport, as role may differ from
698 // In current implementaion we just return the role of first transport in the
700 for (cricket::TransportMap::const_iterator iter = transport_proxies().begin();
701 iter != transport_proxies().end(); ++iter) {
702 if (iter->second->impl()) {
703 return iter->second->impl()->GetSslRole(role);
709 void WebRtcSession::CreateOffer(
710 CreateSessionDescriptionObserver* observer,
711 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
712 webrtc_session_desc_factory_->CreateOffer(observer, options);
715 void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
716 const MediaConstraintsInterface* constraints) {
717 webrtc_session_desc_factory_->CreateAnswer(observer, constraints);
720 bool WebRtcSession::SetLocalDescription(SessionDescriptionInterface* desc,
721 std::string* err_desc) {
722 // Takes the ownership of |desc| regardless of the result.
723 rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
726 if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
730 // Update the initiator flag if this session is the initiator.
731 Action action = GetAction(desc->type());
732 if (state() == STATE_INIT && action == kOffer) {
736 cricket::SecurePolicy sdes_policy =
737 webrtc_session_desc_factory_->SdesPolicy();
738 cricket::CryptoType crypto_required = dtls_enabled_ ?
739 cricket::CT_DTLS : (sdes_policy == cricket::SEC_REQUIRED ?
740 cricket::CT_SDES : cricket::CT_NONE);
741 // Update the MediaContentDescription crypto settings as per the policy set.
742 UpdateSessionDescriptionSecurePolicy(crypto_required, desc->description());
744 set_local_description(desc->description()->Copy());
745 local_desc_.reset(desc_temp.release());
747 // Transport and Media channels will be created only when offer is set.
748 if (action == kOffer && !CreateChannels(local_desc_->description())) {
749 // TODO(mallinath) - Handle CreateChannel failure, as new local description
750 // is applied. Restore back to old description.
751 return BadLocalSdp(desc->type(), kCreateChannelFailed, err_desc);
754 // Remove channel and transport proxies, if MediaContentDescription is
756 RemoveUnusedChannelsAndTransports(local_desc_->description());
758 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
761 // Kick starting the ice candidates allocation.
762 StartCandidatesAllocation();
764 // Update state and SSRC of local MediaStreams and DataChannels based on the
765 // local session description.
766 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
769 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
770 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
772 if (error() != cricket::BaseSession::ERROR_NONE) {
773 return BadLocalSdp(desc->type(), GetSessionErrorMsg(), err_desc);
778 bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
779 std::string* err_desc) {
780 // Takes the ownership of |desc| regardless of the result.
781 rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
784 if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
788 // Transport and Media channels will be created only when offer is set.
789 Action action = GetAction(desc->type());
790 if (action == kOffer && !CreateChannels(desc->description())) {
791 // TODO(mallinath) - Handle CreateChannel failure, as new local description
792 // is applied. Restore back to old description.
793 return BadRemoteSdp(desc->type(), kCreateChannelFailed, err_desc);
796 // Remove channel and transport proxies, if MediaContentDescription is
798 RemoveUnusedChannelsAndTransports(desc->description());
800 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
802 set_remote_description(desc->description()->Copy());
803 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
807 // Update remote MediaStreams.
808 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
809 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
810 return BadRemoteSdp(desc->type(), kInvalidCandidates, err_desc);
813 // Copy all saved candidates.
814 CopySavedCandidates(desc);
815 // We retain all received candidates.
816 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
817 remote_desc_.get(), desc);
818 // Check if this new SessionDescription contains new ice ufrag and password
819 // that indicates the remote peer requests ice restart.
820 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(),
822 remote_desc_.reset(desc_temp.release());
825 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
826 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
829 if (error() != cricket::BaseSession::ERROR_NONE) {
830 return BadRemoteSdp(desc->type(), GetSessionErrorMsg(), err_desc);
835 bool WebRtcSession::UpdateSessionState(
836 Action action, cricket::ContentSource source,
837 std::string* err_desc) {
838 // If there's already a pending error then no state transition should happen.
839 // But all call-sites should be verifying this before calling us!
840 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
842 if (action == kOffer) {
843 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
844 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
846 SetState(source == cricket::CS_LOCAL ?
847 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
848 if (error() != cricket::BaseSession::ERROR_NONE) {
849 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
851 } else if (action == kPrAnswer) {
852 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
853 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
856 SetState(source == cricket::CS_LOCAL ?
857 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
858 if (error() != cricket::BaseSession::ERROR_NONE) {
859 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
861 } else if (action == kAnswer) {
862 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
863 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
865 MaybeEnableMuxingSupport();
867 SetState(source == cricket::CS_LOCAL ?
868 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
869 if (error() != cricket::BaseSession::ERROR_NONE) {
870 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
876 WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
877 if (type == SessionDescriptionInterface::kOffer) {
878 return WebRtcSession::kOffer;
879 } else if (type == SessionDescriptionInterface::kPrAnswer) {
880 return WebRtcSession::kPrAnswer;
881 } else if (type == SessionDescriptionInterface::kAnswer) {
882 return WebRtcSession::kAnswer;
884 ASSERT(false && "unknown action type");
885 return WebRtcSession::kOffer;
888 bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
889 if (state() == STATE_INIT) {
890 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
891 << "without any offer (local or remote) "
892 << "session description.";
897 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
902 if (!ReadyToUseRemoteCandidate(candidate, NULL, &valid)) {
904 LOG(LS_INFO) << "ProcessIceMessage: Candidate saved";
905 saved_candidates_.push_back(
906 new JsepIceCandidate(candidate->sdp_mid(),
907 candidate->sdp_mline_index(),
908 candidate->candidate()));
913 // Add this candidate to the remote session description.
914 if (!remote_desc_->AddCandidate(candidate)) {
915 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
919 return UseCandidate(candidate);
922 bool WebRtcSession::UpdateIce(PeerConnectionInterface::IceTransportsType type) {
926 bool WebRtcSession::GetLocalTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
927 if (!BaseSession::local_description())
929 return webrtc::GetTrackIdBySsrc(
930 BaseSession::local_description(), ssrc, track_id);
933 bool WebRtcSession::GetRemoteTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
934 if (!BaseSession::remote_description())
936 return webrtc::GetTrackIdBySsrc(
937 BaseSession::remote_description(), ssrc, track_id);
940 std::string WebRtcSession::BadStateErrMsg(State state) {
941 std::ostringstream desc;
942 desc << "Called in wrong state: " << GetStateString(state);
946 void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable,
947 cricket::AudioRenderer* renderer) {
948 ASSERT(signaling_thread()->IsCurrent());
949 if (!voice_channel_) {
950 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
953 if (!voice_channel_->SetRemoteRenderer(ssrc, renderer)) {
954 // SetRenderer() can fail if the ssrc does not match any playout channel.
955 LOG(LS_ERROR) << "SetAudioPlayout: ssrc is incorrect: " << ssrc;
958 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
959 // Allow that SetOutputScaling fail if |enable| is false but assert
960 // otherwise. This in the normal case when the underlying media channel has
961 // already been deleted.
962 ASSERT(enable == false);
966 void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
967 const cricket::AudioOptions& options,
968 cricket::AudioRenderer* renderer) {
969 ASSERT(signaling_thread()->IsCurrent());
970 if (!voice_channel_) {
971 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
974 if (!voice_channel_->SetLocalRenderer(ssrc, renderer)) {
975 // SetRenderer() can fail if the ssrc does not match any send channel.
976 LOG(LS_ERROR) << "SetAudioSend: ssrc is incorrect: " << ssrc;
979 if (!voice_channel_->MuteStream(ssrc, !enable)) {
980 // Allow that MuteStream fail if |enable| is false but assert otherwise.
981 // This in the normal case when the underlying media channel has already
983 ASSERT(enable == false);
987 voice_channel_->SetChannelOptions(options);
990 void WebRtcSession::SetAudioPlayoutVolume(uint32 ssrc, double volume) {
991 ASSERT(signaling_thread()->IsCurrent());
992 ASSERT(volume >= 0 && volume <= 10);
993 if (!voice_channel_) {
994 LOG(LS_ERROR) << "SetAudioPlayoutVolume: No audio channel exists.";
998 if (!voice_channel_->SetOutputScaling(ssrc, volume, volume))
1002 bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
1003 cricket::VideoCapturer* camera) {
1004 ASSERT(signaling_thread()->IsCurrent());
1006 if (!video_channel_.get()) {
1007 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
1009 LOG(LS_WARNING) << "Video not used in this call.";
1012 if (!video_channel_->SetCapturer(ssrc, camera)) {
1013 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
1014 // This in the normal case when the underlying media channel has already
1016 ASSERT(camera == NULL);
1022 void WebRtcSession::SetVideoPlayout(uint32 ssrc,
1024 cricket::VideoRenderer* renderer) {
1025 ASSERT(signaling_thread()->IsCurrent());
1026 if (!video_channel_) {
1027 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
1030 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
1031 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
1032 // This in the normal case when the underlying media channel has already
1034 ASSERT(renderer == NULL);
1038 void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
1039 const cricket::VideoOptions* options) {
1040 ASSERT(signaling_thread()->IsCurrent());
1041 if (!video_channel_) {
1042 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
1045 if (!video_channel_->MuteStream(ssrc, !enable)) {
1046 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1047 // This in the normal case when the underlying media channel has already
1049 ASSERT(enable == false);
1052 if (enable && options)
1053 video_channel_->SetChannelOptions(*options);
1056 bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
1057 ASSERT(signaling_thread()->IsCurrent());
1058 if (!voice_channel_) {
1059 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
1062 uint32 send_ssrc = 0;
1063 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
1065 if (!GetAudioSsrcByTrackId(BaseSession::local_description(), track_id,
1067 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1070 return voice_channel_->CanInsertDtmf();
1073 bool WebRtcSession::InsertDtmf(const std::string& track_id,
1074 int code, int duration) {
1075 ASSERT(signaling_thread()->IsCurrent());
1076 if (!voice_channel_) {
1077 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1080 uint32 send_ssrc = 0;
1081 if (!VERIFY(GetAudioSsrcByTrackId(BaseSession::local_description(),
1082 track_id, &send_ssrc))) {
1083 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1086 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1087 cricket::DF_SEND)) {
1088 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1094 sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1095 return &SignalVoiceChannelDestroyed;
1098 bool WebRtcSession::SendData(const cricket::SendDataParams& params,
1099 const rtc::Buffer& payload,
1100 cricket::SendDataResult* result) {
1101 if (!data_channel_.get()) {
1102 LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
1105 return data_channel_->SendData(params, payload, result);
1108 bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
1109 if (!data_channel_.get()) {
1110 LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
1113 data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
1114 &DataChannel::OnChannelReady);
1115 data_channel_->SignalDataReceived.connect(webrtc_data_channel,
1116 &DataChannel::OnDataReceived);
1120 void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
1121 if (!data_channel_.get()) {
1122 LOG(LS_ERROR) << "DisconnectDataChannel called when data_channel_ is NULL.";
1125 data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
1126 data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
1129 void WebRtcSession::AddSctpDataStream(uint32 sid) {
1130 if (!data_channel_.get()) {
1131 LOG(LS_ERROR) << "AddDataChannelStreams called when data_channel_ is NULL.";
1134 data_channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(sid));
1135 data_channel_->AddSendStream(cricket::StreamParams::CreateLegacy(sid));
1138 void WebRtcSession::RemoveSctpDataStream(uint32 sid) {
1139 mediastream_signaling_->RemoveSctpDataChannel(static_cast<int>(sid));
1141 if (!data_channel_.get()) {
1142 LOG(LS_ERROR) << "RemoveDataChannelStreams called when data_channel_ is "
1146 data_channel_->RemoveRecvStream(sid);
1147 data_channel_->RemoveSendStream(sid);
1150 bool WebRtcSession::ReadyToSendData() const {
1151 return data_channel_.get() && data_channel_->ready_to_send_data();
1154 rtc::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
1155 const std::string& label,
1156 const InternalDataChannelInit* config) {
1157 if (state() == STATE_RECEIVEDTERMINATE) {
1160 if (data_channel_type_ == cricket::DCT_NONE) {
1161 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1164 InternalDataChannelInit new_config =
1165 config ? (*config) : InternalDataChannelInit();
1166 if (data_channel_type_ == cricket::DCT_SCTP) {
1167 if (new_config.id < 0) {
1169 if (GetSslRole(&role) &&
1170 !mediastream_signaling_->AllocateSctpSid(role, &new_config.id)) {
1171 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1174 } else if (!mediastream_signaling_->IsSctpSidAvailable(new_config.id)) {
1175 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1176 << "because the id is already in use or out of range.";
1181 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1182 this, data_channel_type_, label, new_config));
1183 if (channel && !mediastream_signaling_->AddDataChannel(channel))
1189 cricket::DataChannelType WebRtcSession::data_channel_type() const {
1190 return data_channel_type_;
1193 bool WebRtcSession::IceRestartPending() const {
1194 return ice_restart_latch_->Get();
1197 void WebRtcSession::ResetIceRestartLatch() {
1198 ice_restart_latch_->Reset();
1201 void WebRtcSession::OnIdentityReady(rtc::SSLIdentity* identity) {
1202 SetIdentity(identity);
1205 bool WebRtcSession::waiting_for_identity() const {
1206 return webrtc_session_desc_factory_->waiting_for_identity();
1209 void WebRtcSession::SetIceConnectionState(
1210 PeerConnectionInterface::IceConnectionState state) {
1211 if (ice_connection_state_ == state) {
1215 // ASSERT that the requested transition is allowed. Note that
1216 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1217 // within PeerConnection). This switch statement should compile away when
1218 // ASSERTs are disabled.
1219 switch (ice_connection_state_) {
1220 case PeerConnectionInterface::kIceConnectionNew:
1221 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1223 case PeerConnectionInterface::kIceConnectionChecking:
1224 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1225 state == PeerConnectionInterface::kIceConnectionConnected);
1227 case PeerConnectionInterface::kIceConnectionConnected:
1228 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1229 state == PeerConnectionInterface::kIceConnectionChecking ||
1230 state == PeerConnectionInterface::kIceConnectionCompleted);
1232 case PeerConnectionInterface::kIceConnectionCompleted:
1233 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1234 state == PeerConnectionInterface::kIceConnectionDisconnected);
1236 case PeerConnectionInterface::kIceConnectionFailed:
1237 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1239 case PeerConnectionInterface::kIceConnectionDisconnected:
1240 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1241 state == PeerConnectionInterface::kIceConnectionConnected ||
1242 state == PeerConnectionInterface::kIceConnectionCompleted ||
1243 state == PeerConnectionInterface::kIceConnectionFailed);
1245 case PeerConnectionInterface::kIceConnectionClosed:
1253 ice_connection_state_ = state;
1254 if (ice_observer_) {
1255 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1259 void WebRtcSession::OnTransportRequestSignaling(
1260 cricket::Transport* transport) {
1261 ASSERT(signaling_thread()->IsCurrent());
1262 transport->OnSignalingReady();
1263 if (ice_observer_) {
1264 ice_observer_->OnIceGatheringChange(
1265 PeerConnectionInterface::kIceGatheringGathering);
1269 void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1270 ASSERT(signaling_thread()->IsCurrent());
1271 // start monitoring for the write state of the transport.
1272 OnTransportWritable(transport);
1275 void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1276 ASSERT(signaling_thread()->IsCurrent());
1277 if (transport->all_channels_writable()) {
1278 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
1279 } else if (transport->HasChannels()) {
1280 // If the current state is Connected or Completed, then there were writable
1281 // channels but now there are not, so the next state must be Disconnected.
1282 if (ice_connection_state_ ==
1283 PeerConnectionInterface::kIceConnectionConnected ||
1284 ice_connection_state_ ==
1285 PeerConnectionInterface::kIceConnectionCompleted) {
1286 SetIceConnectionState(
1287 PeerConnectionInterface::kIceConnectionDisconnected);
1292 void WebRtcSession::OnTransportCompleted(cricket::Transport* transport) {
1293 ASSERT(signaling_thread()->IsCurrent());
1294 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
1297 void WebRtcSession::OnTransportFailed(cricket::Transport* transport) {
1298 ASSERT(signaling_thread()->IsCurrent());
1299 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
1302 void WebRtcSession::OnTransportProxyCandidatesReady(
1303 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1304 ASSERT(signaling_thread()->IsCurrent());
1305 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1308 void WebRtcSession::OnCandidatesAllocationDone() {
1309 ASSERT(signaling_thread()->IsCurrent());
1310 if (ice_observer_) {
1311 ice_observer_->OnIceGatheringChange(
1312 PeerConnectionInterface::kIceGatheringComplete);
1313 ice_observer_->OnIceComplete();
1317 // Enabling voice and video channel.
1318 void WebRtcSession::EnableChannels() {
1319 if (voice_channel_ && !voice_channel_->enabled())
1320 voice_channel_->Enable(true);
1322 if (video_channel_ && !video_channel_->enabled())
1323 video_channel_->Enable(true);
1325 if (data_channel_.get() && !data_channel_->enabled())
1326 data_channel_->Enable(true);
1329 void WebRtcSession::ProcessNewLocalCandidate(
1330 const std::string& content_name,
1331 const cricket::Candidates& candidates) {
1332 int sdp_mline_index;
1333 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1334 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1335 << content_name << " not found";
1339 for (cricket::Candidates::const_iterator citer = candidates.begin();
1340 citer != candidates.end(); ++citer) {
1341 // Use content_name as the candidate media id.
1342 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1343 if (ice_observer_) {
1344 ice_observer_->OnIceCandidate(&candidate);
1347 local_desc_->AddCandidate(&candidate);
1352 // Returns the media index for a local ice candidate given the content name.
1353 bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1354 int* sdp_mline_index) {
1355 if (!BaseSession::local_description() || !sdp_mline_index)
1358 bool content_found = false;
1359 const ContentInfos& contents = BaseSession::local_description()->contents();
1360 for (size_t index = 0; index < contents.size(); ++index) {
1361 if (contents[index].name == content_name) {
1362 *sdp_mline_index = static_cast<int>(index);
1363 content_found = true;
1367 return content_found;
1370 bool WebRtcSession::UseCandidatesInSessionDescription(
1371 const SessionDescriptionInterface* remote_desc) {
1376 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1377 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1378 for (size_t n = 0; n < candidates->count(); ++n) {
1379 const IceCandidateInterface* candidate = candidates->at(n);
1381 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
1383 LOG(LS_INFO) << "UseCandidatesInSessionDescription: Candidate saved.";
1384 saved_candidates_.push_back(
1385 new JsepIceCandidate(candidate->sdp_mid(),
1386 candidate->sdp_mline_index(),
1387 candidate->candidate()));
1392 ret = UseCandidate(candidate);
1400 bool WebRtcSession::UseCandidate(
1401 const IceCandidateInterface* candidate) {
1403 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
1404 size_t remote_content_size =
1405 BaseSession::remote_description()->contents().size();
1406 if (mediacontent_index >= remote_content_size) {
1408 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1412 cricket::ContentInfo content =
1413 BaseSession::remote_description()->contents()[mediacontent_index];
1414 std::vector<cricket::Candidate> candidates;
1415 candidates.push_back(candidate->candidate());
1416 // Invoking BaseSession method to handle remote candidates.
1418 if (OnRemoteCandidates(content.name, candidates, &error)) {
1419 // Candidates successfully submitted for checking.
1420 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1421 ice_connection_state_ ==
1422 PeerConnectionInterface::kIceConnectionDisconnected) {
1423 // If state is New, then the session has just gotten its first remote ICE
1424 // candidates, so go to Checking.
1425 // If state is Disconnected, the session is re-using old candidates or
1426 // receiving additional ones, so go to Checking.
1427 // If state is Connected, stay Connected.
1428 // TODO(bemasc): If state is Connected, and the new candidates are for a
1429 // newly added transport, then the state actually _should_ move to
1430 // checking. Add a way to distinguish that case.
1431 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1433 // TODO(bemasc): If state is Completed, go back to Connected.
1435 if (!error.empty()) {
1436 LOG(LS_WARNING) << error;
1442 void WebRtcSession::RemoveUnusedChannelsAndTransports(
1443 const SessionDescription* desc) {
1444 const cricket::ContentInfo* voice_info =
1445 cricket::GetFirstAudioContent(desc);
1446 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1447 mediastream_signaling_->OnAudioChannelClose();
1448 SignalVoiceChannelDestroyed();
1449 const std::string content_name = voice_channel_->content_name();
1450 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
1451 DestroyTransportProxy(content_name);
1454 const cricket::ContentInfo* video_info =
1455 cricket::GetFirstVideoContent(desc);
1456 if ((!video_info || video_info->rejected) && video_channel_) {
1457 mediastream_signaling_->OnVideoChannelClose();
1458 SignalVideoChannelDestroyed();
1459 const std::string content_name = video_channel_->content_name();
1460 channel_manager_->DestroyVideoChannel(video_channel_.release());
1461 DestroyTransportProxy(content_name);
1464 const cricket::ContentInfo* data_info =
1465 cricket::GetFirstDataContent(desc);
1466 if ((!data_info || data_info->rejected) && data_channel_) {
1467 mediastream_signaling_->OnDataChannelClose();
1468 SignalDataChannelDestroyed();
1469 const std::string content_name = data_channel_->content_name();
1470 channel_manager_->DestroyDataChannel(data_channel_.release());
1471 DestroyTransportProxy(content_name);
1475 // TODO(mallinath) - Add a correct error code if the channels are not creatued
1476 // due to BUNDLE is enabled but rtcp-mux is disabled.
1477 bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
1478 // Disabling the BUNDLE flag in PortAllocator if offer disabled it.
1479 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1480 if (state() == STATE_INIT && !bundle_enabled) {
1481 port_allocator()->set_flags(port_allocator()->flags() &
1482 ~cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1485 // Creating the media channels and transport proxies.
1486 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1487 if (voice && !voice->rejected && !voice_channel_) {
1488 if (!CreateVoiceChannel(voice)) {
1489 LOG(LS_ERROR) << "Failed to create voice channel.";
1494 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1495 if (video && !video->rejected && !video_channel_) {
1496 if (!CreateVideoChannel(video)) {
1497 LOG(LS_ERROR) << "Failed to create video channel.";
1502 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1503 if (data_channel_type_ != cricket::DCT_NONE &&
1504 data && !data->rejected && !data_channel_.get()) {
1505 if (!CreateDataChannel(data)) {
1506 LOG(LS_ERROR) << "Failed to create data channel.";
1514 bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
1515 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
1516 this, content->name, true));
1517 if (!voice_channel_.get())
1520 voice_channel_->SetChannelOptions(audio_options_);
1524 bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
1525 video_channel_.reset(channel_manager_->CreateVideoChannel(
1526 this, content->name, true, voice_channel_.get()));
1527 if (!video_channel_.get())
1530 video_channel_->SetChannelOptions(video_options_);
1534 bool WebRtcSession::CreateDataChannel(const cricket::ContentInfo* content) {
1535 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
1536 data_channel_.reset(channel_manager_->CreateDataChannel(
1537 this, content->name, !sctp, data_channel_type_));
1538 if (!data_channel_.get()) {
1542 mediastream_signaling_->OnDataTransportCreatedForSctp();
1543 data_channel_->SignalDataReceived.connect(
1544 this, &WebRtcSession::OnDataChannelMessageReceived);
1545 data_channel_->SignalStreamClosedRemotely.connect(
1546 mediastream_signaling_,
1547 &MediaStreamSignaling::OnRemoteSctpDataChannelClosed);
1552 void WebRtcSession::CopySavedCandidates(
1553 SessionDescriptionInterface* dest_desc) {
1558 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1559 dest_desc->AddCandidate(saved_candidates_[i]);
1560 delete saved_candidates_[i];
1562 saved_candidates_.clear();
1565 void WebRtcSession::OnDataChannelMessageReceived(
1566 cricket::DataChannel* channel,
1567 const cricket::ReceiveDataParams& params,
1568 const rtc::Buffer& payload) {
1569 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
1570 if (params.type == cricket::DMT_CONTROL &&
1571 mediastream_signaling_->IsSctpSidAvailable(params.ssrc)) {
1572 // Received CONTROL on unused sid, process as an OPEN message.
1573 mediastream_signaling_->AddDataChannelFromOpenMessage(params, payload);
1575 // otherwise ignore the message.
1578 // Returns false if bundle is enabled and rtcp_mux is disabled.
1579 bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
1580 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1581 if (!bundle_enabled)
1584 const cricket::ContentGroup* bundle_group =
1585 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1586 ASSERT(bundle_group != NULL);
1588 const cricket::ContentInfos& contents = desc->contents();
1589 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1590 citer != contents.end(); ++citer) {
1591 const cricket::ContentInfo* content = (&*citer);
1592 ASSERT(content != NULL);
1593 if (bundle_group->HasContentName(content->name) &&
1594 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1595 if (!HasRtcpMuxEnabled(content))
1599 // RTCP-MUX is enabled in all the contents.
1603 bool WebRtcSession::HasRtcpMuxEnabled(
1604 const cricket::ContentInfo* content) {
1605 const cricket::MediaContentDescription* description =
1606 static_cast<cricket::MediaContentDescription*>(content->description);
1607 return description->rtcp_mux();
1610 bool WebRtcSession::ValidateSessionDescription(
1611 const SessionDescriptionInterface* sdesc,
1612 cricket::ContentSource source, std::string* err_desc) {
1614 if (error() != cricket::BaseSession::ERROR_NONE) {
1615 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
1618 if (!sdesc || !sdesc->description()) {
1619 return BadSdp(source, type, kInvalidSdp, err_desc);
1622 type = sdesc->type();
1623 Action action = GetAction(sdesc->type());
1624 if (source == cricket::CS_LOCAL) {
1625 if (!ExpectSetLocalDescription(action))
1626 return BadLocalSdp(type, BadStateErrMsg(state()), err_desc);
1628 if (!ExpectSetRemoteDescription(action))
1629 return BadRemoteSdp(type, BadStateErrMsg(state()), err_desc);
1632 // Verify crypto settings.
1633 std::string crypto_error;
1634 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
1636 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
1637 return BadSdp(source, type, crypto_error, err_desc);
1640 // Verify ice-ufrag and ice-pwd.
1641 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
1642 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
1645 if (!ValidateBundleSettings(sdesc->description())) {
1646 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
1649 // Verify m-lines in Answer when compared against Offer.
1650 if (action == kAnswer) {
1651 const cricket::SessionDescription* offer_desc =
1652 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1653 local_description()->description();
1654 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
1655 return BadAnswerSdp(source, kMlineMismatch, err_desc);
1662 bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1663 return ((action == kOffer && state() == STATE_INIT) ||
1664 // update local offer
1665 (action == kOffer && state() == STATE_SENTINITIATE) ||
1666 // update the current ongoing session.
1667 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1668 (action == kOffer && state() == STATE_SENTACCEPT) ||
1669 (action == kOffer && state() == STATE_INPROGRESS) ||
1670 // accept remote offer
1671 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1672 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1673 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1674 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1677 bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1678 return ((action == kOffer && state() == STATE_INIT) ||
1679 // update remote offer
1680 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1681 // update the current ongoing session
1682 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1683 (action == kOffer && state() == STATE_SENTACCEPT) ||
1684 (action == kOffer && state() == STATE_INPROGRESS) ||
1685 // accept local offer
1686 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1687 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1688 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1689 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1692 std::string WebRtcSession::GetSessionErrorMsg() {
1693 std::ostringstream desc;
1694 desc << kSessionError << GetErrorCodeString(error()) << ". ";
1695 desc << kSessionErrorDesc << error_desc() << ".";
1699 // We need to check the local/remote description for the Transport instead of
1700 // the session, because a new Transport added during renegotiation may have
1701 // them unset while the session has them set from the previous negotiation.
1702 // Not doing so may trigger the auto generation of transport description and
1703 // mess up DTLS identity information, ICE credential, etc.
1704 bool WebRtcSession::ReadyToUseRemoteCandidate(
1705 const IceCandidateInterface* candidate,
1706 const SessionDescriptionInterface* remote_desc,
1709 cricket::TransportProxy* transport_proxy = NULL;
1711 const SessionDescriptionInterface* current_remote_desc =
1712 remote_desc ? remote_desc : remote_description();
1714 if (!current_remote_desc)
1717 size_t mediacontent_index =
1718 static_cast<size_t>(candidate->sdp_mline_index());
1719 size_t remote_content_size =
1720 current_remote_desc->description()->contents().size();
1721 if (mediacontent_index >= remote_content_size) {
1723 << "ReadyToUseRemoteCandidate: Invalid candidate media index.";
1729 cricket::ContentInfo content =
1730 current_remote_desc->description()->contents()[mediacontent_index];
1731 transport_proxy = GetTransportProxy(content.name);
1733 return transport_proxy && transport_proxy->local_description_set() &&
1734 transport_proxy->remote_description_set();
1737 } // namespace webrtc