Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / libjingle / source / talk / app / webrtc / webrtcsession.cc
1 /*
2  * libjingle
3  * Copyright 2012, Google Inc.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  *  1. Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  *  2. Redistributions in binary form must reproduce the above copyright notice,
11  *     this list of conditions and the following disclaimer in the documentation
12  *     and/or other materials provided with the distribution.
13  *  3. The name of the author may not be used to endorse or promote products
14  *     derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19  * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include "talk/app/webrtc/webrtcsession.h"
29
30 #include <limits.h>
31
32 #include <algorithm>
33 #include <vector>
34
35 #include "talk/app/webrtc/jsepicecandidate.h"
36 #include "talk/app/webrtc/jsepsessiondescription.h"
37 #include "talk/app/webrtc/mediaconstraintsinterface.h"
38 #include "talk/app/webrtc/mediastreamsignaling.h"
39 #include "talk/app/webrtc/peerconnectioninterface.h"
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"
51
52 using cricket::ContentInfo;
53 using cricket::ContentInfos;
54 using cricket::MediaContentDescription;
55 using cricket::SessionDescription;
56 using cricket::TransportInfo;
57
58 namespace webrtc {
59
60 // Error messages
61 const char kBundleWithoutRtcpMux[] = "RTCP-MUX must be enabled when BUNDLE "
62                                      "is enabled.";
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;
79
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())
86     return false;
87
88   for (size_t i = 0; i < offer->contents().size(); ++i) {
89     if ((offer->contents()[i].name) != answer->contents()[i].name) {
90       return false;
91     }
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()) {
99       return false;
100     }
101   }
102   return true;
103 }
104
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,
110                          bool dtls_enabled,
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) {
116       continue;
117     }
118
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;
127       return false;
128     }
129     if (dtls_enabled) {
130       if (!tinfo->description.identity_fingerprint) {
131         LOG(LS_WARNING) <<
132             "Session description must have DTLS fingerprint if DTLS enabled.";
133         *error = kSdpWithoutDtlsFingerprint;
134         return false;
135       }
136     } else {
137       if (media->cryptos().empty()) {
138         LOG(LS_WARNING) <<
139             "Session description must have SDES when DTLS disabled.";
140         *error = kSdpWithoutSdesCrypto;
141         return false;
142       }
143     }
144   }
145
146   return true;
147 }
148
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) {
155       continue;
156     }
157
158     // If the content isn't rejected, ice-ufrag and ice-pwd must be present.
159     const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
160     if (!tinfo) {
161       // Something is not right.
162       LOG(LS_ERROR) << kInvalidSdp;
163       return false;
164     }
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.";
168       return false;
169     }
170   }
171   return true;
172 }
173
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) {
180   if (!sdesc) {
181     return;
182   }
183
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);
191       if (mdesc) {
192         mdesc->set_crypto_required(type);
193       }
194     }
195   }
196 }
197
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);
203   if (!audio_info) {
204     LOG(LS_ERROR) << "Audio not used in this call";
205     return false;
206   }
207
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,
213                                &stream)) {
214     return false;
215   }
216   *ssrc = stream.first_ssrc();
217   return true;
218 }
219
220 static bool GetTrackIdBySsrc(const SessionDescription* session_description,
221                              uint32 ssrc, std::string* track_id) {
222   ASSERT(track_id != NULL);
223
224   cricket::StreamParams stream_out;
225   const cricket::ContentInfo* audio_info =
226       cricket::GetFirstAudioContent(session_description);
227   if (!audio_info) {
228     return false;
229   }
230   const cricket::MediaContentDescription* audio_content =
231       static_cast<const cricket::MediaContentDescription*>(
232           audio_info->description);
233
234   if (cricket::GetStreamBySsrc(audio_content->streams(), ssrc, &stream_out)) {
235     *track_id = stream_out.id;
236     return true;
237   }
238
239   const cricket::ContentInfo* video_info =
240       cricket::GetFirstVideoContent(session_description);
241   if (!video_info) {
242     return false;
243   }
244   const cricket::MediaContentDescription* video_content =
245       static_cast<const cricket::MediaContentDescription*>(
246           video_info->description);
247
248   if (cricket::GetStreamBySsrc(video_content->streams(), ssrc, &stream_out)) {
249     *track_id = stream_out.id;
250     return true;
251   }
252   return false;
253 }
254
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;
261
262   if (err_desc) {
263     *err_desc = desc.str();
264   }
265   LOG(LS_ERROR) << desc.str();
266   return false;
267 }
268
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);
275   } else {
276     return BadSdp("remote", type, reason, err_desc);
277   }
278 }
279
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);
284 }
285
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);
290 }
291
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);
296 }
297
298 static bool BadPranswerSdp(cricket::ContentSource source,
299                            const std::string& reason,
300                            std::string* err_desc) {
301   return BadSdp(source, SessionDescriptionInterface::kPrAnswer,
302                 reason, err_desc);
303 }
304
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);
309 }
310
311 #define GET_STRING_OF_STATE(state)  \
312   case cricket::BaseSession::state:  \
313     result = #state;  \
314     break;
315
316 static std::string GetStateString(cricket::BaseSession::State state) {
317   std::string result;
318   switch (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)
335     default:
336       ASSERT(false);
337       break;
338   }
339   return result;
340 }
341
342 #define GET_STRING_OF_ERROR_CODE(err)  \
343   case cricket::BaseSession::err:  \
344     result = #err;  \
345     break;
346
347 static std::string GetErrorCodeString(cricket::BaseSession::Error err) {
348   std::string result;
349   switch (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)
356     default:
357       ASSERT(false);
358       break;
359   }
360   return result;
361 }
362
363 static std::string MakeErrorString(const std::string& error,
364                                    const std::string& desc) {
365   std::ostringstream ret;
366   ret << error << " " << desc;
367   return ret.str();
368 }
369
370 static std::string MakeTdErrorString(const std::string& desc) {
371   return MakeErrorString(kPushDownTDFailed, desc);
372 }
373
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.
376 template<typename T>
377 static void SetOptionFromOptionalConstraint(
378     const MediaConstraintsInterface* constraints,
379     const std::string& key, cricket::Settable<T>* option) {
380   if (!constraints) {
381     return;
382   }
383   std::string string_value;
384   T value;
385   if (constraints->GetOptional().FindFirst(key, &string_value)) {
386     if (rtc::FromString(string_value, &value)) {
387       option->Set(value);
388     }
389   }
390 }
391
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 {
395  public:
396   IceRestartAnswerLatch() : ice_restart_(false) { }
397
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.
401   bool Get() const {
402     return ice_restart_;
403   }
404
405   void Reset() {
406     if (ice_restart_) {
407       ice_restart_ = false;
408     }
409   }
410
411   void CheckForRemoteIceRestart(
412       const SessionDescriptionInterface* old_desc,
413       const SessionDescriptionInterface* new_desc) {
414     if (!old_desc || new_desc->type() != SessionDescriptionInterface::kOffer) {
415       return;
416     }
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) {
423         continue;
424       }
425       // If the content isn't rejected, check if ufrag and password has
426       // changed.
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.
433         continue;
434       }
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.";
440         ice_restart_ = true;
441         break;
442       }
443     }
444   }
445
446  private:
447   bool ice_restart_;
448 };
449
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() &
458                                                LLONG_MAX),
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),
465       ice_observer_(NULL),
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) {
471 }
472
473 WebRtcSession::~WebRtcSession() {
474   if (voice_channel_.get()) {
475     SignalVoiceChannelDestroyed();
476     channel_manager_->DestroyVoiceChannel(voice_channel_.release());
477   }
478   if (video_channel_.get()) {
479     SignalVideoChannelDestroyed();
480     channel_manager_->DestroyVideoChannel(video_channel_.release());
481   }
482   if (data_channel_.get()) {
483     SignalDataChannelDestroyed();
484     channel_manager_->DestroyDataChannel(data_channel_.release());
485   }
486   for (size_t i = 0; i < saved_candidates_.size(); ++i) {
487     delete saved_candidates_[i];
488   }
489   delete identity();
490 }
491
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|
499   // can be null.
500   bool value;
501
502   if (options.disable_encryption) {
503     dtls_enabled_ = false;
504   } else {
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.
508     if (FindConstraint(
509           constraints,
510           MediaConstraintsInterface::kEnableDtlsSrtp,
511           &value, NULL)) {
512       dtls_enabled_ = value;
513     }
514   }
515
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.
519   if (FindConstraint(
520       constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
521       &value, NULL) && value) {
522     LOG(LS_INFO) << "Allowing RTP data engine.";
523     data_channel_type_ = cricket::DCT_RTP;
524   } else {
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;
529     }
530   }
531   if (data_channel_type_ != cricket::DCT_NONE) {
532     mediastream_signaling_->SetDataChannelFactory(this);
533   }
534
535   // Find DSCP constraint.
536   if (FindConstraint(
537         constraints,
538         MediaConstraintsInterface::kEnableDscp,
539         &value, NULL)) {
540     audio_options_.dscp.Set(value);
541     video_options_.dscp.Set(value);
542   }
543
544   // Find Suspend Below Min Bitrate constraint.
545   if (FindConstraint(
546           constraints,
547           MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate,
548           &value,
549           NULL)) {
550     video_options_.suspend_below_min_bitrate.Set(value);
551   }
552
553   SetOptionFromOptionalConstraint(constraints,
554       MediaConstraintsInterface::kScreencastMinBitrate,
555       &video_options_.screencast_min_bitrate);
556
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);
576
577   // Find payload padding constraint.
578   SetOptionFromOptionalConstraint(constraints,
579       MediaConstraintsInterface::kPayloadPadding,
580       &video_options_.use_payload_padding);
581
582   // Find improved wifi bwe constraint.
583   if (FindConstraint(
584         constraints,
585         MediaConstraintsInterface::kImprovedWifiBwe,
586         &value,
587         NULL)) {
588     video_options_.use_improved_wifi_bandwidth_estimator.Set(value);
589   } else {
590     // Enable by default if the constraint is not set.
591     video_options_.use_improved_wifi_bandwidth_estimator.Set(true);
592   }
593
594   SetOptionFromOptionalConstraint(constraints,
595       MediaConstraintsInterface::kNumUnsignalledRecvStreams,
596       &video_options_.unsignalled_recv_stream_limit);
597   if (video_options_.unsignalled_recv_stream_limit.IsSet()) {
598     int stream_limit;
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);
603   }
604
605   SetOptionFromOptionalConstraint(constraints,
606       MediaConstraintsInterface::kHighStartBitrate,
607       &video_options_.video_start_bitrate);
608
609   if (FindConstraint(
610       constraints,
611       MediaConstraintsInterface::kVeryHighBitrate,
612       &value,
613       NULL)) {
614     video_options_.video_highest_bitrate.Set(
615         cricket::VideoOptions::VERY_HIGH);
616   } else if (FindConstraint(
617       constraints,
618       MediaConstraintsInterface::kHighBitrate,
619       &value,
620       NULL)) {
621     video_options_.video_highest_bitrate.Set(
622         cricket::VideoOptions::HIGH);
623   }
624
625   SetOptionFromOptionalConstraint(constraints,
626       MediaConstraintsInterface::kOpusFec,
627       &audio_options_.opus_fec);
628
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));
638
639   webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
640       signaling_thread(),
641       channel_manager_,
642       mediastream_signaling_,
643       dtls_identity_service,
644       this,
645       id(),
646       data_channel_type_,
647       dtls_enabled_));
648
649   webrtc_session_desc_factory_->SignalIdentityReady.connect(
650       this, &WebRtcSession::OnIdentityReady);
651
652   if (options.disable_encryption) {
653     webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
654   }
655
656   return true;
657 }
658
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);
665 }
666
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());
675   }
676   // Push remote candidates present in remote description to transport channels.
677   UseCandidatesInSessionDescription(remote_desc_.get());
678   return true;
679 }
680
681 void WebRtcSession::SetSdesPolicy(cricket::SecurePolicy secure_policy) {
682   webrtc_session_desc_factory_->SetSdesPolicy(secure_policy);
683 }
684
685 cricket::SecurePolicy WebRtcSession::SdesPolicy() const {
686   return webrtc_session_desc_factory_->SdesPolicy();
687 }
688
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.";
693     return false;
694   }
695
696   // TODO(mallinath) - Return role of each transport, as role may differ from
697   // one another.
698   // In current implementaion we just return the role of first transport in the
699   // transport map.
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);
704     }
705   }
706   return false;
707 }
708
709 void WebRtcSession::CreateOffer(
710     CreateSessionDescriptionObserver* observer,
711     const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
712   webrtc_session_desc_factory_->CreateOffer(observer, options);
713 }
714
715 void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
716                                  const MediaConstraintsInterface* constraints) {
717   webrtc_session_desc_factory_->CreateAnswer(observer, constraints);
718 }
719
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);
724
725   // Validate SDP.
726   if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
727     return false;
728   }
729
730   // Update the initiator flag if this session is the initiator.
731   Action action = GetAction(desc->type());
732   if (state() == STATE_INIT && action == kOffer) {
733     set_initiator(true);
734   }
735
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());
743
744   set_local_description(desc->description()->Copy());
745   local_desc_.reset(desc_temp.release());
746
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);
752   }
753
754   // Remove channel and transport proxies, if MediaContentDescription is
755   // rejected.
756   RemoveUnusedChannelsAndTransports(local_desc_->description());
757
758   if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
759     return false;
760   }
761   // Kick starting the ice candidates allocation.
762   StartCandidatesAllocation();
763
764   // Update state and SSRC of local MediaStreams and DataChannels based on the
765   // local session description.
766   mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
767
768   rtc::SSLRole role;
769   if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
770     mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
771   }
772   if (error() != cricket::BaseSession::ERROR_NONE) {
773     return BadLocalSdp(desc->type(), GetSessionErrorMsg(), err_desc);
774   }
775   return true;
776 }
777
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);
782
783   // Validate SDP.
784   if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
785     return false;
786   }
787
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);
794   }
795
796   // Remove channel and transport proxies, if MediaContentDescription is
797   // rejected.
798   RemoveUnusedChannelsAndTransports(desc->description());
799
800   // NOTE: Candidates allocation will be initiated only when SetLocalDescription
801   // is called.
802   set_remote_description(desc->description()->Copy());
803   if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
804     return false;
805   }
806
807   // Update remote MediaStreams.
808   mediastream_signaling_->OnRemoteDescriptionChanged(desc);
809   if (local_description() && !UseCandidatesInSessionDescription(desc)) {
810     return BadRemoteSdp(desc->type(), kInvalidCandidates, err_desc);
811   }
812
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(),
821                                                desc);
822   remote_desc_.reset(desc_temp.release());
823
824   rtc::SSLRole role;
825   if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
826     mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
827   }
828
829   if (error() != cricket::BaseSession::ERROR_NONE) {
830     return BadRemoteSdp(desc->type(), GetSessionErrorMsg(), err_desc);
831   }
832   return true;
833 }
834
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);
841   std::string td_err;
842   if (action == kOffer) {
843     if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
844       return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
845     }
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);
850     }
851   } else if (action == kPrAnswer) {
852     if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
853       return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
854     }
855     EnableChannels();
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);
860     }
861   } else if (action == kAnswer) {
862     if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
863       return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
864     }
865     MaybeEnableMuxingSupport();
866     EnableChannels();
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);
871     }
872   }
873   return true;
874 }
875
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;
883   }
884   ASSERT(false && "unknown action type");
885   return WebRtcSession::kOffer;
886 }
887
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.";
893      return false;
894   }
895
896   if (!candidate) {
897     LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
898     return false;
899   }
900
901   bool valid = false;
902   if (!ReadyToUseRemoteCandidate(candidate, NULL, &valid)) {
903     if (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()));
909     }
910     return valid;
911   }
912
913   // Add this candidate to the remote session description.
914   if (!remote_desc_->AddCandidate(candidate)) {
915     LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
916     return false;
917   }
918
919   return UseCandidate(candidate);
920 }
921
922 bool WebRtcSession::UpdateIce(PeerConnectionInterface::IceTransportsType type) {
923   return false;
924 }
925
926 bool WebRtcSession::GetLocalTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
927   if (!BaseSession::local_description())
928     return false;
929   return webrtc::GetTrackIdBySsrc(
930       BaseSession::local_description(), ssrc, track_id);
931 }
932
933 bool WebRtcSession::GetRemoteTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
934   if (!BaseSession::remote_description())
935     return false;
936   return webrtc::GetTrackIdBySsrc(
937       BaseSession::remote_description(), ssrc, track_id);
938 }
939
940 std::string WebRtcSession::BadStateErrMsg(State state) {
941   std::ostringstream desc;
942   desc << "Called in wrong state: " << GetStateString(state);
943   return desc.str();
944 }
945
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.";
951     return;
952   }
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;
956     return;
957   }
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);
963   }
964 }
965
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.";
972     return;
973   }
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;
977     return;
978   }
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
982     // been deleted.
983     ASSERT(enable == false);
984     return;
985   }
986   if (enable)
987     voice_channel_->SetChannelOptions(options);
988 }
989
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.";
995     return;
996   }
997
998   if (!voice_channel_->SetOutputScaling(ssrc, volume, volume))
999     ASSERT(false);
1000 }
1001
1002 bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
1003                                      cricket::VideoCapturer* camera) {
1004   ASSERT(signaling_thread()->IsCurrent());
1005
1006   if (!video_channel_.get()) {
1007     // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
1008     // support video.
1009     LOG(LS_WARNING) << "Video not used in this call.";
1010     return false;
1011   }
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
1015     // been deleted.
1016     ASSERT(camera == NULL);
1017     return false;
1018   }
1019   return true;
1020 }
1021
1022 void WebRtcSession::SetVideoPlayout(uint32 ssrc,
1023                                     bool enable,
1024                                     cricket::VideoRenderer* renderer) {
1025   ASSERT(signaling_thread()->IsCurrent());
1026   if (!video_channel_) {
1027     LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
1028     return;
1029   }
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
1033     // been deleted.
1034     ASSERT(renderer == NULL);
1035   }
1036 }
1037
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.";
1043     return;
1044   }
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
1048     // been deleted.
1049     ASSERT(enable == false);
1050     return;
1051   }
1052   if (enable && options)
1053     video_channel_->SetChannelOptions(*options);
1054 }
1055
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.";
1060     return false;
1061   }
1062   uint32 send_ssrc = 0;
1063   // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
1064   // exists.
1065   if (!GetAudioSsrcByTrackId(BaseSession::local_description(), track_id,
1066                              &send_ssrc)) {
1067     LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1068     return false;
1069   }
1070   return voice_channel_->CanInsertDtmf();
1071 }
1072
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.";
1078     return false;
1079   }
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;
1084     return false;
1085   }
1086   if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1087                                   cricket::DF_SEND)) {
1088     LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1089     return false;
1090   }
1091   return true;
1092 }
1093
1094 sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1095   return &SignalVoiceChannelDestroyed;
1096 }
1097
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.";
1103     return false;
1104   }
1105   return data_channel_->SendData(params, payload, result);
1106 }
1107
1108 bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
1109   if (!data_channel_.get()) {
1110     LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
1111     return false;
1112   }
1113   data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
1114                                                &DataChannel::OnChannelReady);
1115   data_channel_->SignalDataReceived.connect(webrtc_data_channel,
1116                                             &DataChannel::OnDataReceived);
1117   return true;
1118 }
1119
1120 void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
1121   if (!data_channel_.get()) {
1122     LOG(LS_ERROR) << "DisconnectDataChannel called when data_channel_ is NULL.";
1123     return;
1124   }
1125   data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
1126   data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
1127 }
1128
1129 void WebRtcSession::AddSctpDataStream(uint32 sid) {
1130   if (!data_channel_.get()) {
1131     LOG(LS_ERROR) << "AddDataChannelStreams called when data_channel_ is NULL.";
1132     return;
1133   }
1134   data_channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(sid));
1135   data_channel_->AddSendStream(cricket::StreamParams::CreateLegacy(sid));
1136 }
1137
1138 void WebRtcSession::RemoveSctpDataStream(uint32 sid) {
1139   mediastream_signaling_->RemoveSctpDataChannel(static_cast<int>(sid));
1140
1141   if (!data_channel_.get()) {
1142     LOG(LS_ERROR) << "RemoveDataChannelStreams called when data_channel_ is "
1143                   << "NULL.";
1144     return;
1145   }
1146   data_channel_->RemoveRecvStream(sid);
1147   data_channel_->RemoveSendStream(sid);
1148 }
1149
1150 bool WebRtcSession::ReadyToSendData() const {
1151   return data_channel_.get() && data_channel_->ready_to_send_data();
1152 }
1153
1154 rtc::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
1155     const std::string& label,
1156     const InternalDataChannelInit* config) {
1157   if (state() == STATE_RECEIVEDTERMINATE) {
1158     return NULL;
1159   }
1160   if (data_channel_type_ == cricket::DCT_NONE) {
1161     LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1162     return NULL;
1163   }
1164   InternalDataChannelInit new_config =
1165       config ? (*config) : InternalDataChannelInit();
1166   if (data_channel_type_ == cricket::DCT_SCTP) {
1167     if (new_config.id < 0) {
1168       rtc::SSLRole role;
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.";
1172         return NULL;
1173       }
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.";
1177       return NULL;
1178     }
1179   }
1180
1181   rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
1182       this, data_channel_type_, label, new_config));
1183   if (channel && !mediastream_signaling_->AddDataChannel(channel))
1184     return NULL;
1185
1186   return channel;
1187 }
1188
1189 cricket::DataChannelType WebRtcSession::data_channel_type() const {
1190   return data_channel_type_;
1191 }
1192
1193 bool WebRtcSession::IceRestartPending() const {
1194   return ice_restart_latch_->Get();
1195 }
1196
1197 void WebRtcSession::ResetIceRestartLatch() {
1198   ice_restart_latch_->Reset();
1199 }
1200
1201 void WebRtcSession::OnIdentityReady(rtc::SSLIdentity* identity) {
1202   SetIdentity(identity);
1203 }
1204
1205 bool WebRtcSession::waiting_for_identity() const {
1206   return webrtc_session_desc_factory_->waiting_for_identity();
1207 }
1208
1209 void WebRtcSession::SetIceConnectionState(
1210       PeerConnectionInterface::IceConnectionState state) {
1211   if (ice_connection_state_ == state) {
1212     return;
1213   }
1214
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);
1222       break;
1223     case PeerConnectionInterface::kIceConnectionChecking:
1224       ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1225              state == PeerConnectionInterface::kIceConnectionConnected);
1226       break;
1227     case PeerConnectionInterface::kIceConnectionConnected:
1228       ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1229              state == PeerConnectionInterface::kIceConnectionChecking ||
1230              state == PeerConnectionInterface::kIceConnectionCompleted);
1231       break;
1232     case PeerConnectionInterface::kIceConnectionCompleted:
1233       ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1234              state == PeerConnectionInterface::kIceConnectionDisconnected);
1235       break;
1236     case PeerConnectionInterface::kIceConnectionFailed:
1237       ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1238       break;
1239     case PeerConnectionInterface::kIceConnectionDisconnected:
1240       ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1241              state == PeerConnectionInterface::kIceConnectionConnected ||
1242              state == PeerConnectionInterface::kIceConnectionCompleted ||
1243              state == PeerConnectionInterface::kIceConnectionFailed);
1244       break;
1245     case PeerConnectionInterface::kIceConnectionClosed:
1246       ASSERT(false);
1247       break;
1248     default:
1249       ASSERT(false);
1250       break;
1251   }
1252
1253   ice_connection_state_ = state;
1254   if (ice_observer_) {
1255     ice_observer_->OnIceConnectionChange(ice_connection_state_);
1256   }
1257 }
1258
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);
1266   }
1267 }
1268
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);
1273 }
1274
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);
1288     }
1289   }
1290 }
1291
1292 void WebRtcSession::OnTransportCompleted(cricket::Transport* transport) {
1293   ASSERT(signaling_thread()->IsCurrent());
1294   SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
1295 }
1296
1297 void WebRtcSession::OnTransportFailed(cricket::Transport* transport) {
1298   ASSERT(signaling_thread()->IsCurrent());
1299   SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
1300 }
1301
1302 void WebRtcSession::OnTransportProxyCandidatesReady(
1303     cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1304   ASSERT(signaling_thread()->IsCurrent());
1305   ProcessNewLocalCandidate(proxy->content_name(), candidates);
1306 }
1307
1308 void WebRtcSession::OnCandidatesAllocationDone() {
1309   ASSERT(signaling_thread()->IsCurrent());
1310   if (ice_observer_) {
1311     ice_observer_->OnIceGatheringChange(
1312       PeerConnectionInterface::kIceGatheringComplete);
1313     ice_observer_->OnIceComplete();
1314   }
1315 }
1316
1317 // Enabling voice and video channel.
1318 void WebRtcSession::EnableChannels() {
1319   if (voice_channel_ && !voice_channel_->enabled())
1320     voice_channel_->Enable(true);
1321
1322   if (video_channel_ && !video_channel_->enabled())
1323     video_channel_->Enable(true);
1324
1325   if (data_channel_.get() && !data_channel_->enabled())
1326     data_channel_->Enable(true);
1327 }
1328
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";
1336     return;
1337   }
1338
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);
1345     }
1346     if (local_desc_) {
1347       local_desc_->AddCandidate(&candidate);
1348     }
1349   }
1350 }
1351
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)
1356     return false;
1357
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;
1364       break;
1365     }
1366   }
1367   return content_found;
1368 }
1369
1370 bool WebRtcSession::UseCandidatesInSessionDescription(
1371     const SessionDescriptionInterface* remote_desc) {
1372   if (!remote_desc)
1373     return true;
1374   bool ret = true;
1375
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);
1380       bool valid = false;
1381       if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
1382         if (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()));
1388         }
1389         continue;
1390       }
1391
1392       ret = UseCandidate(candidate);
1393       if (!ret)
1394         break;
1395     }
1396   }
1397   return ret;
1398 }
1399
1400 bool WebRtcSession::UseCandidate(
1401     const IceCandidateInterface* candidate) {
1402
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) {
1407     LOG(LS_ERROR)
1408         << "UseRemoteCandidateInSession: Invalid candidate media index.";
1409     return false;
1410   }
1411
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.
1417   std::string error;
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);
1432     }
1433     // TODO(bemasc): If state is Completed, go back to Connected.
1434   } else {
1435     if (!error.empty()) {
1436       LOG(LS_WARNING) << error;
1437     }
1438   }
1439   return true;
1440 }
1441
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);
1452   }
1453
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);
1462   }
1463
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);
1472   }
1473 }
1474
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);
1483   }
1484
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.";
1490       return false;
1491     }
1492   }
1493
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.";
1498       return false;
1499     }
1500   }
1501
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.";
1507       return false;
1508     }
1509   }
1510
1511   return true;
1512 }
1513
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())
1518     return false;
1519
1520   voice_channel_->SetChannelOptions(audio_options_);
1521   return true;
1522 }
1523
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())
1528     return false;
1529
1530   video_channel_->SetChannelOptions(video_options_);
1531   return true;
1532 }
1533
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()) {
1539     return false;
1540   }
1541   if (sctp) {
1542     mediastream_signaling_->OnDataTransportCreatedForSctp();
1543     data_channel_->SignalDataReceived.connect(
1544         this, &WebRtcSession::OnDataChannelMessageReceived);
1545     data_channel_->SignalStreamClosedRemotely.connect(
1546         mediastream_signaling_,
1547         &MediaStreamSignaling::OnRemoteSctpDataChannelClosed);
1548   }
1549   return true;
1550 }
1551
1552 void WebRtcSession::CopySavedCandidates(
1553     SessionDescriptionInterface* dest_desc) {
1554   if (!dest_desc) {
1555     ASSERT(false);
1556     return;
1557   }
1558   for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1559     dest_desc->AddCandidate(saved_candidates_[i]);
1560     delete saved_candidates_[i];
1561   }
1562   saved_candidates_.clear();
1563 }
1564
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);
1574   }
1575   // otherwise ignore the message.
1576 }
1577
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)
1582     return true;
1583
1584   const cricket::ContentGroup* bundle_group =
1585       desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1586   ASSERT(bundle_group != NULL);
1587
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))
1596         return false;
1597     }
1598   }
1599   // RTCP-MUX is enabled in all the contents.
1600   return true;
1601 }
1602
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();
1608 }
1609
1610 bool WebRtcSession::ValidateSessionDescription(
1611     const SessionDescriptionInterface* sdesc,
1612     cricket::ContentSource source, std::string* err_desc) {
1613   std::string type;
1614   if (error() != cricket::BaseSession::ERROR_NONE) {
1615     return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
1616   }
1617
1618   if (!sdesc || !sdesc->description()) {
1619     return BadSdp(source, type, kInvalidSdp, err_desc);
1620   }
1621
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);
1627   } else {
1628     if (!ExpectSetRemoteDescription(action))
1629       return BadRemoteSdp(type, BadStateErrMsg(state()), err_desc);
1630   }
1631
1632   // Verify crypto settings.
1633   std::string crypto_error;
1634   if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
1635        dtls_enabled_) &&
1636       !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
1637     return BadSdp(source, type, crypto_error, err_desc);
1638   }
1639
1640   // Verify ice-ufrag and ice-pwd.
1641   if (!VerifyIceUfragPwdPresent(sdesc->description())) {
1642     return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
1643   }
1644
1645   if (!ValidateBundleSettings(sdesc->description())) {
1646     return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
1647   }
1648
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);
1656     }
1657   }
1658
1659   return true;
1660 }
1661
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));
1675 }
1676
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));
1690 }
1691
1692 std::string WebRtcSession::GetSessionErrorMsg() {
1693   std::ostringstream desc;
1694   desc << kSessionError << GetErrorCodeString(error()) << ". ";
1695   desc << kSessionErrorDesc << error_desc() << ".";
1696   return desc.str();
1697 }
1698
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,
1707     bool* valid) {
1708   *valid = true;;
1709   cricket::TransportProxy* transport_proxy = NULL;
1710
1711   const SessionDescriptionInterface* current_remote_desc =
1712       remote_desc ? remote_desc : remote_description();
1713
1714   if (!current_remote_desc)
1715     return false;
1716
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) {
1722     LOG(LS_ERROR)
1723         << "ReadyToUseRemoteCandidate: Invalid candidate media index.";
1724
1725     *valid = false;
1726     return false;
1727   }
1728
1729   cricket::ContentInfo content =
1730       current_remote_desc->description()->contents()[mediacontent_index];
1731   transport_proxy = GetTransportProxy(content.name);
1732
1733   return transport_proxy && transport_proxy->local_description_set() &&
1734       transport_proxy->remote_description_set();
1735 }
1736
1737 }  // namespace webrtc