blob: fee8d42fc555129741f84972d6e069baa55c9566 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2012, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/app/webrtc/webrtcsession.h"
29
30#include <algorithm>
31#include <climits>
32#include <vector>
33
34#include "talk/app/webrtc/jsepicecandidate.h"
35#include "talk/app/webrtc/jsepsessiondescription.h"
36#include "talk/app/webrtc/mediaconstraintsinterface.h"
37#include "talk/app/webrtc/mediastreamsignaling.h"
38#include "talk/app/webrtc/peerconnectioninterface.h"
39#include "talk/base/helpers.h"
40#include "talk/base/logging.h"
41#include "talk/base/stringencode.h"
42#include "talk/media/base/constants.h"
43#include "talk/media/base/videocapturer.h"
44#include "talk/session/media/channel.h"
45#include "talk/session/media/channelmanager.h"
46#include "talk/session/media/mediasession.h"
47
48using cricket::ContentInfo;
49using cricket::ContentInfos;
50using cricket::MediaContentDescription;
51using cricket::SessionDescription;
52using cricket::TransportInfo;
53
54typedef cricket::MediaSessionOptions::Stream Stream;
55typedef cricket::MediaSessionOptions::Streams Streams;
56
57namespace webrtc {
58
59static const uint64 kInitSessionVersion = 2;
60
61const char kInternalConstraintPrefix[] = "internal";
62
63// Supported MediaConstraints.
64// DTLS-SRTP pseudo-constraints.
65const char MediaConstraintsInterface::kEnableDtlsSrtp[] =
66 "DtlsSrtpKeyAgreement";
67// DataChannel pseudo constraints.
68const char MediaConstraintsInterface::kEnableRtpDataChannels[] =
69 "RtpDataChannels";
70// This constraint is for internal use only, representing the Chrome command
71// line flag. So it is prefixed with kInternalConstraintPrefix so JS values
72// will be removed.
73const char MediaConstraintsInterface::kEnableSctpDataChannels[] =
74 "internalSctpDataChannels";
75
76// Arbitrary constant used as prefix for the identity.
77// Chosen to make the certificates more readable.
78const char kWebRTCIdentityPrefix[] = "WebRTC";
79
80// Error messages
81const char kSetLocalSdpFailed[] = "SetLocalDescription failed: ";
82const char kSetRemoteSdpFailed[] = "SetRemoteDescription failed: ";
83const char kCreateChannelFailed[] = "Failed to create channels.";
84const char kInvalidCandidates[] = "Description contains invalid candidates.";
85const char kInvalidSdp[] = "Invalid session description.";
86const char kMlineMismatch[] =
87 "Offer and answer descriptions m-lines are not matching. "
88 "Rejecting answer.";
89const char kSdpWithoutCrypto[] = "Called with a SDP without crypto enabled.";
90const char kSessionError[] = "Session error code: ";
91const char kUpdateStateFailed[] = "Failed to update session state: ";
92const char kPushDownOfferTDFailed[] =
93 "Failed to push down offer transport description.";
94const char kPushDownPranswerTDFailed[] =
95 "Failed to push down pranswer transport description.";
96const char kPushDownAnswerTDFailed[] =
97 "Failed to push down answer transport description.";
98
99// Compares |answer| against |offer|. Comparision is done
100// for number of m-lines in answer against offer. If matches true will be
101// returned otherwise false.
102static bool VerifyMediaDescriptions(
103 const SessionDescription* answer, const SessionDescription* offer) {
104 if (offer->contents().size() != answer->contents().size())
105 return false;
106
107 for (size_t i = 0; i < offer->contents().size(); ++i) {
108 if ((offer->contents()[i].name) != answer->contents()[i].name) {
109 return false;
110 }
111 }
112 return true;
113}
114
115static void CopyCandidatesFromSessionDescription(
116 const SessionDescriptionInterface* source_desc,
117 SessionDescriptionInterface* dest_desc) {
118 if (!source_desc)
119 return;
120 for (size_t m = 0; m < source_desc->number_of_mediasections() &&
121 m < dest_desc->number_of_mediasections(); ++m) {
122 const IceCandidateCollection* source_candidates =
123 source_desc->candidates(m);
124 const IceCandidateCollection* dest_candidates = dest_desc->candidates(m);
125 for (size_t n = 0; n < source_candidates->count(); ++n) {
126 const IceCandidateInterface* new_candidate = source_candidates->at(n);
127 if (!dest_candidates->HasCandidate(new_candidate))
128 dest_desc->AddCandidate(source_candidates->at(n));
129 }
130 }
131}
132
133// Checks that each non-rejected content has SDES crypto keys or a DTLS
134// fingerprint. Mismatches, such as replying with a DTLS fingerprint to SDES
135// keys, will be caught in Transport negotiation, and backstopped by Channel's
136// |secure_required| check.
137static bool VerifyCrypto(const SessionDescription* desc) {
138 if (!desc) {
139 return false;
140 }
141 const ContentInfos& contents = desc->contents();
142 for (size_t index = 0; index < contents.size(); ++index) {
143 const ContentInfo* cinfo = &contents[index];
144 if (cinfo->rejected) {
145 continue;
146 }
147
148 // If the content isn't rejected, crypto must be present.
149 const MediaContentDescription* media =
150 static_cast<const MediaContentDescription*>(cinfo->description);
151 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
152 if (!media || !tinfo) {
153 // Something is not right.
154 LOG(LS_ERROR) << kInvalidSdp;
155 return false;
156 }
157 if (media->cryptos().empty() &&
158 !tinfo->description.identity_fingerprint) {
159 // Crypto must be supplied.
160 LOG(LS_WARNING) << "Session description must have SDES or DTLS-SRTP.";
161 return false;
162 }
163 }
164
165 return true;
166}
167
168static bool CompareStream(const Stream& stream1, const Stream& stream2) {
169 return (stream1.id < stream2.id);
170}
171
172static bool SameId(const Stream& stream1, const Stream& stream2) {
173 return (stream1.id == stream2.id);
174}
175
176// Checks if each Stream within the |streams| has unique id.
177static bool ValidStreams(const Streams& streams) {
178 Streams sorted_streams = streams;
179 std::sort(sorted_streams.begin(), sorted_streams.end(), CompareStream);
180 Streams::iterator it =
181 std::adjacent_find(sorted_streams.begin(), sorted_streams.end(),
182 SameId);
183 return (it == sorted_streams.end());
184}
185
186static bool GetAudioSsrcByTrackId(
187 const SessionDescription* session_description,
188 const std::string& track_id, uint32 *ssrc) {
189 const cricket::ContentInfo* audio_info =
190 cricket::GetFirstAudioContent(session_description);
191 if (!audio_info) {
192 LOG(LS_ERROR) << "Audio not used in this call";
193 return false;
194 }
195
196 const cricket::MediaContentDescription* audio_content =
197 static_cast<const cricket::MediaContentDescription*>(
198 audio_info->description);
199 cricket::StreamParams stream;
200 if (!cricket::GetStreamByIds(audio_content->streams(), "", track_id,
201 &stream)) {
202 return false;
203 }
204 *ssrc = stream.first_ssrc();
205 return true;
206}
207
208static bool GetTrackIdBySsrc(const SessionDescription* session_description,
209 uint32 ssrc, std::string* track_id) {
210 ASSERT(track_id != NULL);
211
212 cricket::StreamParams stream_out;
213 const cricket::ContentInfo* audio_info =
214 cricket::GetFirstAudioContent(session_description);
215 if (!audio_info) {
216 return false;
217 }
218 const cricket::MediaContentDescription* audio_content =
219 static_cast<const cricket::MediaContentDescription*>(
220 audio_info->description);
221
222 if (cricket::GetStreamBySsrc(audio_content->streams(), ssrc, &stream_out)) {
223 *track_id = stream_out.id;
224 return true;
225 }
226
227 const cricket::ContentInfo* video_info =
228 cricket::GetFirstVideoContent(session_description);
229 if (!video_info) {
230 return false;
231 }
232 const cricket::MediaContentDescription* video_content =
233 static_cast<const cricket::MediaContentDescription*>(
234 video_info->description);
235
236 if (cricket::GetStreamBySsrc(video_content->streams(), ssrc, &stream_out)) {
237 *track_id = stream_out.id;
238 return true;
239 }
240 return false;
241}
242
243static bool BadSdp(const std::string& desc, std::string* err_desc) {
244 if (err_desc) {
245 *err_desc = desc;
246 }
247 LOG(LS_ERROR) << desc;
248 return false;
249}
250
251static bool BadLocalSdp(const std::string& desc, std::string* err_desc) {
252 std::string set_local_sdp_failed = kSetLocalSdpFailed;
253 set_local_sdp_failed.append(desc);
254 return BadSdp(set_local_sdp_failed, err_desc);
255}
256
257static bool BadRemoteSdp(const std::string& desc, std::string* err_desc) {
258 std::string set_remote_sdp_failed = kSetRemoteSdpFailed;
259 set_remote_sdp_failed.append(desc);
260 return BadSdp(set_remote_sdp_failed, err_desc);
261}
262
263static bool BadSdp(cricket::ContentSource source,
264 const std::string& desc, std::string* err_desc) {
265 if (source == cricket::CS_LOCAL) {
266 return BadLocalSdp(desc, err_desc);
267 } else {
268 return BadRemoteSdp(desc, err_desc);
269 }
270}
271
272static std::string SessionErrorMsg(cricket::BaseSession::Error error) {
273 std::ostringstream desc;
274 desc << kSessionError << error;
275 return desc.str();
276}
277
278#define GET_STRING_OF_STATE(state) \
279 case cricket::BaseSession::state: \
280 result = #state; \
281 break;
282
283static std::string GetStateString(cricket::BaseSession::State state) {
284 std::string result;
285 switch (state) {
286 GET_STRING_OF_STATE(STATE_INIT)
287 GET_STRING_OF_STATE(STATE_SENTINITIATE)
288 GET_STRING_OF_STATE(STATE_RECEIVEDINITIATE)
289 GET_STRING_OF_STATE(STATE_SENTPRACCEPT)
290 GET_STRING_OF_STATE(STATE_SENTACCEPT)
291 GET_STRING_OF_STATE(STATE_RECEIVEDPRACCEPT)
292 GET_STRING_OF_STATE(STATE_RECEIVEDACCEPT)
293 GET_STRING_OF_STATE(STATE_SENTMODIFY)
294 GET_STRING_OF_STATE(STATE_RECEIVEDMODIFY)
295 GET_STRING_OF_STATE(STATE_SENTREJECT)
296 GET_STRING_OF_STATE(STATE_RECEIVEDREJECT)
297 GET_STRING_OF_STATE(STATE_SENTREDIRECT)
298 GET_STRING_OF_STATE(STATE_SENTTERMINATE)
299 GET_STRING_OF_STATE(STATE_RECEIVEDTERMINATE)
300 GET_STRING_OF_STATE(STATE_INPROGRESS)
301 GET_STRING_OF_STATE(STATE_DEINIT)
302 default:
303 ASSERT(false);
304 break;
305 }
306 return result;
307}
308
309#define GET_STRING_OF_ERROR(err) \
310 case cricket::BaseSession::err: \
311 result = #err; \
312 break;
313
314static std::string GetErrorString(cricket::BaseSession::Error err) {
315 std::string result;
316 switch (err) {
317 GET_STRING_OF_ERROR(ERROR_NONE)
318 GET_STRING_OF_ERROR(ERROR_TIME)
319 GET_STRING_OF_ERROR(ERROR_RESPONSE)
320 GET_STRING_OF_ERROR(ERROR_NETWORK)
321 GET_STRING_OF_ERROR(ERROR_CONTENT)
322 GET_STRING_OF_ERROR(ERROR_TRANSPORT)
323 default:
324 ASSERT(false);
325 break;
326 }
327 return result;
328}
329
330static bool SetSessionStateFailed(cricket::ContentSource source,
331 cricket::BaseSession::Error err,
332 std::string* err_desc) {
333 std::string set_state_err = kUpdateStateFailed;
334 set_state_err.append(GetErrorString(err));
335 return BadSdp(source, set_state_err, err_desc);
336}
337
338// Help class used to remember if a a remote peer has requested ice restart by
339// by sending a description with new ice ufrag and password.
340class IceRestartAnswerLatch {
341 public:
342 IceRestartAnswerLatch() : ice_restart_(false) { }
343
344 // Returns true if CheckForRemoteIceRestart has been called since last
345 // time this method was called with a new session description where
346 // ice password and ufrag has changed.
347 bool AnswerWithIceRestartLatch() {
348 if (ice_restart_) {
349 ice_restart_ = false;
350 return true;
351 }
352 return false;
353 }
354
355 void CheckForRemoteIceRestart(
356 const SessionDescriptionInterface* old_desc,
357 const SessionDescriptionInterface* new_desc) {
358 if (!old_desc || new_desc->type() != SessionDescriptionInterface::kOffer) {
359 return;
360 }
361 const SessionDescription* new_sd = new_desc->description();
362 const SessionDescription* old_sd = old_desc->description();
363 const ContentInfos& contents = new_sd->contents();
364 for (size_t index = 0; index < contents.size(); ++index) {
365 const ContentInfo* cinfo = &contents[index];
366 if (cinfo->rejected) {
367 continue;
368 }
369 // If the content isn't rejected, check if ufrag and password has
370 // changed.
371 const cricket::TransportDescription* new_transport_desc =
372 new_sd->GetTransportDescriptionByName(cinfo->name);
373 const cricket::TransportDescription* old_transport_desc =
374 old_sd->GetTransportDescriptionByName(cinfo->name);
375 if (!new_transport_desc || !old_transport_desc) {
376 // No transport description exist. This is not an ice restart.
377 continue;
378 }
379 if (new_transport_desc->ice_pwd != old_transport_desc->ice_pwd &&
380 new_transport_desc->ice_ufrag != old_transport_desc->ice_ufrag) {
381 LOG(LS_INFO) << "Remote peer request ice restart.";
382 ice_restart_ = true;
383 break;
384 }
385 }
386 }
387
388 private:
389 bool ice_restart_;
390};
391
392WebRtcSession::WebRtcSession(cricket::ChannelManager* channel_manager,
393 talk_base::Thread* signaling_thread,
394 talk_base::Thread* worker_thread,
395 cricket::PortAllocator* port_allocator,
396 MediaStreamSignaling* mediastream_signaling)
397 : cricket::BaseSession(signaling_thread, worker_thread, port_allocator,
398 talk_base::ToString(talk_base::CreateRandomId64() &
399 LLONG_MAX),
400 cricket::NS_JINGLE_RTP, false),
401 // RFC 3264: The numeric value of the session id and version in the
402 // o line MUST be representable with a "64 bit signed integer".
403 // Due to this constraint session id |sid_| is max limited to LLONG_MAX.
404 channel_manager_(channel_manager),
405 session_desc_factory_(channel_manager, &transport_desc_factory_),
406 mediastream_signaling_(mediastream_signaling),
407 ice_observer_(NULL),
408 ice_connection_state_(PeerConnectionInterface::kIceConnectionNew),
409 // RFC 4566 suggested a Network Time Protocol (NTP) format timestamp
410 // as the session id and session version. To simplify, it should be fine
411 // to just use a random number as session id and start version from
412 // |kInitSessionVersion|.
413 session_version_(kInitSessionVersion),
414 older_version_remote_peer_(false),
415 data_channel_type_(cricket::DCT_NONE),
416 ice_restart_latch_(new IceRestartAnswerLatch) {
417 transport_desc_factory_.set_protocol(cricket::ICEPROTO_HYBRID);
418}
419
420WebRtcSession::~WebRtcSession() {
421 if (voice_channel_.get()) {
422 SignalVoiceChannelDestroyed();
423 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
424 }
425 if (video_channel_.get()) {
426 SignalVideoChannelDestroyed();
427 channel_manager_->DestroyVideoChannel(video_channel_.release());
428 }
429 if (data_channel_.get()) {
430 SignalDataChannelDestroyed();
431 channel_manager_->DestroyDataChannel(data_channel_.release());
432 }
433 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
434 delete saved_candidates_[i];
435 }
436 delete identity();
437 set_identity(NULL);
438 transport_desc_factory_.set_identity(NULL);
439}
440
441bool WebRtcSession::Initialize(const MediaConstraintsInterface* constraints) {
442 // TODO(perkj): Take |constraints| into consideration. Return false if not all
443 // mandatory constraints can be fulfilled. Note that |constraints|
444 // can be null.
445
446 // By default SRTP-SDES is enabled in WebRtc.
447 set_secure_policy(cricket::SEC_REQUIRED);
448
449 // Enable DTLS-SRTP if the constraint is set.
450 bool value;
451 if (FindConstraint(constraints, MediaConstraintsInterface::kEnableDtlsSrtp,
452 &value, NULL) && value) {
453 LOG(LS_INFO) << "DTLS-SRTP enabled; generating identity";
454 std::string identity_name = kWebRTCIdentityPrefix +
455 talk_base::ToString(talk_base::CreateRandomId());
456 transport_desc_factory_.set_identity(talk_base::SSLIdentity::Generate(
457 identity_name));
458 LOG(LS_INFO) << "Finished generating identity";
459 set_identity(transport_desc_factory_.identity());
460 transport_desc_factory_.set_digest_algorithm(talk_base::DIGEST_SHA_256);
461
462 transport_desc_factory_.set_secure(cricket::SEC_ENABLED);
463 }
464
465 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
466 // It takes precendence over the kEnableSctpDataChannels constraint.
467 if (FindConstraint(
468 constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
469 &value, NULL) && value) {
470 LOG(LS_INFO) << "Allowing RTP data engine.";
471 data_channel_type_ = cricket::DCT_RTP;
472 } else if (
473 FindConstraint(
474 constraints,
475 MediaConstraintsInterface::kEnableSctpDataChannels,
476 &value, NULL) && value &&
477 // DTLS has to be enabled to use SCTP.
478 (transport_desc_factory_.secure() == cricket::SEC_ENABLED)) {
479 LOG(LS_INFO) << "Allowing SCTP data engine.";
480 data_channel_type_ = cricket::DCT_SCTP;
481 }
482 if (data_channel_type_ != cricket::DCT_NONE) {
483 mediastream_signaling_->SetDataChannelFactory(this);
484 }
485
486 // Make sure SessionDescriptions only contains the StreamParams we negotiate.
487 session_desc_factory_.set_add_legacy_streams(false);
488
489 const cricket::VideoCodec default_codec(
490 JsepSessionDescription::kDefaultVideoCodecId,
491 JsepSessionDescription::kDefaultVideoCodecName,
492 JsepSessionDescription::kMaxVideoCodecWidth,
493 JsepSessionDescription::kMaxVideoCodecHeight,
494 JsepSessionDescription::kDefaultVideoCodecFramerate,
495 JsepSessionDescription::kDefaultVideoCodecPreference);
496 channel_manager_->SetDefaultVideoEncoderConfig(
497 cricket::VideoEncoderConfig(default_codec));
498 return true;
499}
500
501void WebRtcSession::Terminate() {
502 SetState(STATE_RECEIVEDTERMINATE);
503 RemoveUnusedChannelsAndTransports(NULL);
504 ASSERT(voice_channel_.get() == NULL);
505 ASSERT(video_channel_.get() == NULL);
506 ASSERT(data_channel_.get() == NULL);
507}
508
509bool WebRtcSession::StartCandidatesAllocation() {
510 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
511 // from TransportProxy to start gathering ice candidates.
512 SpeculativelyConnectAllTransportChannels();
513 if (!saved_candidates_.empty()) {
514 // If there are saved candidates which arrived before local description is
515 // set, copy those to remote description.
516 CopySavedCandidates(remote_desc_.get());
517 }
518 // Push remote candidates present in remote description to transport channels.
519 UseCandidatesInSessionDescription(remote_desc_.get());
520 return true;
521}
522
523void WebRtcSession::set_secure_policy(
524 cricket::SecureMediaPolicy secure_policy) {
525 session_desc_factory_.set_secure(secure_policy);
526}
527
528SessionDescriptionInterface* WebRtcSession::CreateOffer(
529 const MediaConstraintsInterface* constraints) {
530 cricket::MediaSessionOptions options;
531
532 if (!mediastream_signaling_->GetOptionsForOffer(constraints, &options)) {
533 LOG(LS_ERROR) << "CreateOffer called with invalid constraints.";
534 return NULL;
535 }
536
537 if (!ValidStreams(options.streams)) {
538 LOG(LS_ERROR) << "CreateOffer called with invalid media streams.";
539 return NULL;
540 }
541
542 if (data_channel_type_ == cricket::DCT_SCTP) {
543 options.data_channel_type = cricket::DCT_SCTP;
544 }
545 SessionDescription* desc(
546 session_desc_factory_.CreateOffer(options,
547 BaseSession::local_description()));
548 // RFC 3264
549 // When issuing an offer that modifies the session,
550 // the "o=" line of the new SDP MUST be identical to that in the
551 // previous SDP, except that the version in the origin field MUST
552 // increment by one from the previous SDP.
553
554 // Just increase the version number by one each time when a new offer
555 // is created regardless if it's identical to the previous one or not.
556 // The |session_version_| is a uint64, the wrap around should not happen.
557 ASSERT(session_version_ + 1 > session_version_);
558 JsepSessionDescription* offer(new JsepSessionDescription(
559 JsepSessionDescription::kOffer));
560 if (!offer->Initialize(desc, id(),
561 talk_base::ToString(session_version_++))) {
562 delete offer;
563 return NULL;
564 }
565 if (local_description() && !options.transport_options.ice_restart) {
566 // Include all local ice candidates in the SessionDescription unless
567 // the an ice restart has been requested.
568 CopyCandidatesFromSessionDescription(local_description(), offer);
569 }
570 return offer;
571}
572
573SessionDescriptionInterface* WebRtcSession::CreateAnswer(
574 const MediaConstraintsInterface* constraints) {
575 if (!remote_description()) {
576 LOG(LS_ERROR) << "CreateAnswer can't be called before"
577 << " SetRemoteDescription.";
578 return NULL;
579 }
580 if (remote_description()->type() != JsepSessionDescription::kOffer) {
581 LOG(LS_ERROR) << "CreateAnswer failed because remote_description is not an"
582 << " offer.";
583 return NULL;
584 }
585
586 cricket::MediaSessionOptions options;
587 if (!mediastream_signaling_->GetOptionsForAnswer(constraints, &options)) {
588 LOG(LS_ERROR) << "CreateAnswer called with invalid constraints.";
589 return NULL;
590 }
591 if (!ValidStreams(options.streams)) {
592 LOG(LS_ERROR) << "CreateAnswer called with invalid media streams.";
593 return NULL;
594 }
595 if (data_channel_type_ == cricket::DCT_SCTP) {
596 options.data_channel_type = cricket::DCT_SCTP;
597 }
598 // According to http://tools.ietf.org/html/rfc5245#section-9.2.1.1
599 // an answer should also contain new ice ufrag and password if an offer has
600 // been received with new ufrag and password.
601 options.transport_options.ice_restart =
602 ice_restart_latch_->AnswerWithIceRestartLatch();
603 SessionDescription* desc(
604 session_desc_factory_.CreateAnswer(BaseSession::remote_description(),
605 options,
606 BaseSession::local_description()));
607 // RFC 3264
608 // If the answer is different from the offer in any way (different IP
609 // addresses, ports, etc.), the origin line MUST be different in the answer.
610 // In that case, the version number in the "o=" line of the answer is
611 // unrelated to the version number in the o line of the offer.
612 // Get a new version number by increasing the |session_version_answer_|.
613 // The |session_version_| is a uint64, the wrap around should not happen.
614 ASSERT(session_version_ + 1 > session_version_);
615 JsepSessionDescription* answer(new JsepSessionDescription(
616 JsepSessionDescription::kAnswer));
617 if (!answer->Initialize(desc, id(),
618 talk_base::ToString(session_version_++))) {
619 delete answer;
620 return NULL;
621 }
622 if (local_description() && !options.transport_options.ice_restart) {
623 // Include all local ice candidates in the SessionDescription unless
624 // the remote peer has requested an ice restart.
625 CopyCandidatesFromSessionDescription(local_description(), answer);
626 }
627 return answer;
628}
629
630bool WebRtcSession::SetLocalDescription(SessionDescriptionInterface* desc,
631 std::string* err_desc) {
632 if (error() != cricket::BaseSession::ERROR_NONE) {
633 delete desc;
634 return BadLocalSdp(SessionErrorMsg(error()), err_desc);
635 }
636
637 if (!desc || !desc->description()) {
638 delete desc;
639 return BadLocalSdp(kInvalidSdp, err_desc);
640 }
641 Action action = GetAction(desc->type());
642 if (!ExpectSetLocalDescription(action)) {
643 std::string type = desc->type();
644 delete desc;
645 return BadLocalSdp(BadStateErrMsg(type, state()), err_desc);
646 }
647
648 if (session_desc_factory_.secure() == cricket::SEC_REQUIRED &&
649 !VerifyCrypto(desc->description())) {
650 delete desc;
651 return BadLocalSdp(kSdpWithoutCrypto, err_desc);
652 }
653
654 if (action == kAnswer && !VerifyMediaDescriptions(
655 desc->description(), remote_description()->description())) {
656 return BadLocalSdp(kMlineMismatch, err_desc);
657 }
658
659 // Update the initiator flag if this session is the initiator.
660 if (state() == STATE_INIT && action == kOffer) {
661 set_initiator(true);
662 }
663
664 // Update the MediaContentDescription crypto settings as per the policy set.
665 UpdateSessionDescriptionSecurePolicy(desc->description());
666
667 set_local_description(desc->description()->Copy());
668 local_desc_.reset(desc);
669
670 // Transport and Media channels will be created only when offer is set.
671 if (action == kOffer && !CreateChannels(desc->description())) {
672 // TODO(mallinath) - Handle CreateChannel failure, as new local description
673 // is applied. Restore back to old description.
674 return BadLocalSdp(kCreateChannelFailed, err_desc);
675 }
676
677 // Remove channel and transport proxies, if MediaContentDescription is
678 // rejected.
679 RemoveUnusedChannelsAndTransports(desc->description());
680
681 if (!UpdateSessionState(action, cricket::CS_LOCAL,
682 desc->description(), err_desc)) {
683 return false;
684 }
685 // Kick starting the ice candidates allocation.
686 StartCandidatesAllocation();
687
688 // Update state and SSRC of local MediaStreams and DataChannels based on the
689 // local session description.
690 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
691
692 if (error() != cricket::BaseSession::ERROR_NONE) {
693 return BadLocalSdp(SessionErrorMsg(error()), err_desc);
694 }
695 return true;
696}
697
698bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
699 std::string* err_desc) {
700 if (error() != cricket::BaseSession::ERROR_NONE) {
701 delete desc;
702 return BadRemoteSdp(SessionErrorMsg(error()), err_desc);
703 }
704
705 if (!desc || !desc->description()) {
706 delete desc;
707 return BadRemoteSdp(kInvalidSdp, err_desc);
708 }
709 Action action = GetAction(desc->type());
710 if (!ExpectSetRemoteDescription(action)) {
711 std::string type = desc->type();
712 delete desc;
713 return BadRemoteSdp(BadStateErrMsg(type, state()), err_desc);
714 }
715
716 if (action == kAnswer && !VerifyMediaDescriptions(
717 desc->description(), local_description()->description())) {
718 return BadRemoteSdp(kMlineMismatch, err_desc);
719 }
720
721 if (session_desc_factory_.secure() == cricket::SEC_REQUIRED &&
722 !VerifyCrypto(desc->description())) {
723 delete desc;
724 return BadRemoteSdp(kSdpWithoutCrypto, err_desc);
725 }
726
727 // Transport and Media channels will be created only when offer is set.
728 if (action == kOffer && !CreateChannels(desc->description())) {
729 // TODO(mallinath) - Handle CreateChannel failure, as new local description
730 // is applied. Restore back to old description.
731 return BadRemoteSdp(kCreateChannelFailed, err_desc);
732 }
733
734 // Remove channel and transport proxies, if MediaContentDescription is
735 // rejected.
736 RemoveUnusedChannelsAndTransports(desc->description());
737
738 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
739 // is called.
740 set_remote_description(desc->description()->Copy());
741 if (!UpdateSessionState(action, cricket::CS_REMOTE,
742 desc->description(), err_desc)) {
743 return false;
744 }
745
746 // Update remote MediaStreams.
747 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
748 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
749 delete desc;
750 return BadRemoteSdp(kInvalidCandidates, err_desc);
751 }
752
753 // Copy all saved candidates.
754 CopySavedCandidates(desc);
755 // We retain all received candidates.
756 CopyCandidatesFromSessionDescription(remote_desc_.get(), desc);
757 // Check if this new SessionDescription contains new ice ufrag and password
758 // that indicates the remote peer requests ice restart.
759 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(),
760 desc);
761 remote_desc_.reset(desc);
762 if (error() != cricket::BaseSession::ERROR_NONE) {
763 return BadRemoteSdp(SessionErrorMsg(error()), err_desc);
764 }
765 return true;
766}
767
768bool WebRtcSession::UpdateSessionState(
769 Action action, cricket::ContentSource source,
770 const cricket::SessionDescription* desc,
771 std::string* err_desc) {
772 // If there's already a pending error then no state transition should happen.
773 // But all call-sites should be verifying this before calling us!
774 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
775 if (action == kOffer) {
776 if (!PushdownTransportDescription(source, cricket::CA_OFFER)) {
777 return BadSdp(source, kPushDownOfferTDFailed, err_desc);
778 }
779 SetState(source == cricket::CS_LOCAL ?
780 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
781 if (error() != cricket::BaseSession::ERROR_NONE) {
782 return SetSessionStateFailed(source, error(), err_desc);
783 }
784 } else if (action == kPrAnswer) {
785 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER)) {
786 return BadSdp(source, kPushDownPranswerTDFailed, err_desc);
787 }
788 EnableChannels();
789 SetState(source == cricket::CS_LOCAL ?
790 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
791 if (error() != cricket::BaseSession::ERROR_NONE) {
792 return SetSessionStateFailed(source, error(), err_desc);
793 }
794 } else if (action == kAnswer) {
795 if (!PushdownTransportDescription(source, cricket::CA_ANSWER)) {
796 return BadSdp(source, kPushDownAnswerTDFailed, err_desc);
797 }
798 MaybeEnableMuxingSupport();
799 EnableChannels();
800 SetState(source == cricket::CS_LOCAL ?
801 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
802 if (error() != cricket::BaseSession::ERROR_NONE) {
803 return SetSessionStateFailed(source, error(), err_desc);
804 }
805 }
806 return true;
807}
808
809WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
810 if (type == SessionDescriptionInterface::kOffer) {
811 return WebRtcSession::kOffer;
812 } else if (type == SessionDescriptionInterface::kPrAnswer) {
813 return WebRtcSession::kPrAnswer;
814 } else if (type == SessionDescriptionInterface::kAnswer) {
815 return WebRtcSession::kAnswer;
816 }
817 ASSERT(false && "unknown action type");
818 return WebRtcSession::kOffer;
819}
820
821bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
822 if (state() == STATE_INIT) {
823 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
824 << "without any offer (local or remote) "
825 << "session description.";
826 return false;
827 }
828
829 if (!candidate) {
830 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
831 return false;
832 }
833
834 if (!local_description() || !remote_description()) {
835 LOG(LS_INFO) << "ProcessIceMessage: Remote description not set, "
836 << "save the candidate for later use.";
837 saved_candidates_.push_back(
838 new JsepIceCandidate(candidate->sdp_mid(), candidate->sdp_mline_index(),
839 candidate->candidate()));
840 return true;
841 }
842
843 // Add this candidate to the remote session description.
844 if (!remote_desc_->AddCandidate(candidate)) {
845 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
846 return false;
847 }
848
849 return UseCandidatesInSessionDescription(remote_desc_.get());
850}
851
852bool WebRtcSession::GetTrackIdBySsrc(uint32 ssrc, std::string* id) {
853 if (GetLocalTrackId(ssrc, id)) {
854 if (GetRemoteTrackId(ssrc, id)) {
855 LOG(LS_WARNING) << "SSRC " << ssrc
856 << " exists in both local and remote descriptions";
857 return true; // We return the remote track id.
858 }
859 return true;
860 } else {
861 return GetRemoteTrackId(ssrc, id);
862 }
863}
864
865bool WebRtcSession::GetLocalTrackId(uint32 ssrc, std::string* track_id) {
866 if (!BaseSession::local_description())
867 return false;
868 return webrtc::GetTrackIdBySsrc(
869 BaseSession::local_description(), ssrc, track_id);
870}
871
872bool WebRtcSession::GetRemoteTrackId(uint32 ssrc, std::string* track_id) {
873 if (!BaseSession::remote_description())
874 return false;
875 return webrtc::GetTrackIdBySsrc(
876 BaseSession::remote_description(), ssrc, track_id);
877}
878
879std::string WebRtcSession::BadStateErrMsg(
880 const std::string& type, State state) {
881 std::ostringstream desc;
882 desc << "Called with type in wrong state, "
883 << "type: " << type << " state: " << GetStateString(state);
884 return desc.str();
885}
886
887void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable) {
888 ASSERT(signaling_thread()->IsCurrent());
889 if (!voice_channel_) {
890 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
891 return;
892 }
893 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
894 // Allow that SetOutputScaling fail if |enable| is false but assert
895 // otherwise. This in the normal case when the underlying media channel has
896 // already been deleted.
897 ASSERT(enable == false);
898 }
899}
900
901void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
902 const cricket::AudioOptions& options) {
903 ASSERT(signaling_thread()->IsCurrent());
904 if (!voice_channel_) {
905 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
906 return;
907 }
908 if (!voice_channel_->MuteStream(ssrc, !enable)) {
909 // Allow that MuteStream fail if |enable| is false but assert otherwise.
910 // This in the normal case when the underlying media channel has already
911 // been deleted.
912 ASSERT(enable == false);
913 return;
914 }
915 if (enable)
916 voice_channel_->SetChannelOptions(options);
917}
918
919bool WebRtcSession::SetAudioRenderer(uint32 ssrc,
920 cricket::AudioRenderer* renderer) {
921 if (!voice_channel_) {
922 LOG(LS_ERROR) << "SetAudioRenderer: No audio channel exists.";
923 return false;
924 }
925
926 if (!voice_channel_->SetRenderer(ssrc, renderer)) {
927 // SetRenderer() can fail if the ssrc is not mapping to the playout channel.
928 LOG(LS_ERROR) << "SetAudioRenderer: ssrc is incorrect: " << ssrc;
929 return false;
930 }
931
932 return true;
933}
934
935bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
936 cricket::VideoCapturer* camera) {
937 ASSERT(signaling_thread()->IsCurrent());
938
939 if (!video_channel_.get()) {
940 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
941 // support video.
942 LOG(LS_WARNING) << "Video not used in this call.";
943 return false;
944 }
945 if (!video_channel_->SetCapturer(ssrc, camera)) {
946 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
947 // This in the normal case when the underlying media channel has already
948 // been deleted.
949 ASSERT(camera == NULL);
950 return false;
951 }
952 return true;
953}
954
955void WebRtcSession::SetVideoPlayout(uint32 ssrc,
956 bool enable,
957 cricket::VideoRenderer* renderer) {
958 ASSERT(signaling_thread()->IsCurrent());
959 if (!video_channel_) {
960 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
961 return;
962 }
963 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
964 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
965 // This in the normal case when the underlying media channel has already
966 // been deleted.
967 ASSERT(renderer == NULL);
968 }
969}
970
971void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
972 const cricket::VideoOptions* options) {
973 ASSERT(signaling_thread()->IsCurrent());
974 if (!video_channel_) {
975 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
976 return;
977 }
978 if (!video_channel_->MuteStream(ssrc, !enable)) {
979 // Allow that MuteStream fail if |enable| is false but assert otherwise.
980 // This in the normal case when the underlying media channel has already
981 // been deleted.
982 ASSERT(enable == false);
983 return;
984 }
985 if (enable && options)
986 video_channel_->SetChannelOptions(*options);
987}
988
989bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
990 ASSERT(signaling_thread()->IsCurrent());
991 if (!voice_channel_) {
992 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
993 return false;
994 }
995 uint32 send_ssrc = 0;
996 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
997 // exists.
998 if (!GetAudioSsrcByTrackId(BaseSession::local_description(), track_id,
999 &send_ssrc)) {
1000 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1001 return false;
1002 }
1003 return voice_channel_->CanInsertDtmf();
1004}
1005
1006bool WebRtcSession::InsertDtmf(const std::string& track_id,
1007 int code, int duration) {
1008 ASSERT(signaling_thread()->IsCurrent());
1009 if (!voice_channel_) {
1010 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1011 return false;
1012 }
1013 uint32 send_ssrc = 0;
1014 if (!VERIFY(GetAudioSsrcByTrackId(BaseSession::local_description(),
1015 track_id, &send_ssrc))) {
1016 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1017 return false;
1018 }
1019 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1020 cricket::DF_SEND)) {
1021 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1022 return false;
1023 }
1024 return true;
1025}
1026
1027sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1028 return &SignalVoiceChannelDestroyed;
1029}
1030
1031talk_base::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
1032 const std::string& label,
1033 const DataChannelInit* config) {
1034 if (state() == STATE_RECEIVEDTERMINATE) {
1035 return NULL;
1036 }
1037 if (data_channel_type_ == cricket::DCT_NONE) {
1038 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1039 return NULL;
1040 }
1041 DataChannelInit new_config = config ? (*config) : DataChannelInit();
1042
1043 if (data_channel_type_ == cricket::DCT_SCTP) {
1044 if (new_config.id < 0) {
1045 if (!mediastream_signaling_->AllocateSctpId(&new_config.id)) {
1046 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1047 return NULL;
1048 }
1049 } else if (!mediastream_signaling_->IsSctpIdAvailable(new_config.id)) {
1050 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1051 << "because the id is already in use or out of range.";
1052 return NULL;
1053 }
1054 }
1055 talk_base::scoped_refptr<DataChannel> channel(
1056 DataChannel::Create(this, label, &new_config));
1057 if (channel == NULL)
1058 return NULL;
1059 if (!mediastream_signaling_->AddDataChannel(channel))
1060 return NULL;
1061 return channel;
1062}
1063
1064cricket::DataChannelType WebRtcSession::data_channel_type() const {
1065 return data_channel_type_;
1066}
1067
1068void WebRtcSession::SetIceConnectionState(
1069 PeerConnectionInterface::IceConnectionState state) {
1070 if (ice_connection_state_ == state) {
1071 return;
1072 }
1073
1074 // ASSERT that the requested transition is allowed. Note that
1075 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1076 // within PeerConnection). This switch statement should compile away when
1077 // ASSERTs are disabled.
1078 switch (ice_connection_state_) {
1079 case PeerConnectionInterface::kIceConnectionNew:
1080 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1081 break;
1082 case PeerConnectionInterface::kIceConnectionChecking:
1083 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1084 state == PeerConnectionInterface::kIceConnectionConnected);
1085 break;
1086 case PeerConnectionInterface::kIceConnectionConnected:
1087 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1088 state == PeerConnectionInterface::kIceConnectionChecking ||
1089 state == PeerConnectionInterface::kIceConnectionCompleted);
1090 break;
1091 case PeerConnectionInterface::kIceConnectionCompleted:
1092 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1093 state == PeerConnectionInterface::kIceConnectionDisconnected);
1094 break;
1095 case PeerConnectionInterface::kIceConnectionFailed:
1096 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1097 break;
1098 case PeerConnectionInterface::kIceConnectionDisconnected:
1099 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1100 state == PeerConnectionInterface::kIceConnectionConnected ||
1101 state == PeerConnectionInterface::kIceConnectionCompleted ||
1102 state == PeerConnectionInterface::kIceConnectionFailed);
1103 break;
1104 case PeerConnectionInterface::kIceConnectionClosed:
1105 ASSERT(false);
1106 break;
1107 default:
1108 ASSERT(false);
1109 break;
1110 }
1111
1112 ice_connection_state_ = state;
1113 if (ice_observer_) {
1114 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1115 }
1116}
1117
1118void WebRtcSession::OnTransportRequestSignaling(
1119 cricket::Transport* transport) {
1120 ASSERT(signaling_thread()->IsCurrent());
1121 transport->OnSignalingReady();
1122 if (ice_observer_) {
1123 ice_observer_->OnIceGatheringChange(
1124 PeerConnectionInterface::kIceGatheringGathering);
1125 }
1126}
1127
1128void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1129 ASSERT(signaling_thread()->IsCurrent());
1130 // start monitoring for the write state of the transport.
1131 OnTransportWritable(transport);
1132}
1133
1134void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1135 ASSERT(signaling_thread()->IsCurrent());
1136 // TODO(bemasc): Expose more API from Transport to detect when
1137 // candidate selection starts or stops, due to success or failure.
1138 if (transport->all_channels_writable()) {
1139 if (ice_connection_state_ ==
1140 PeerConnectionInterface::kIceConnectionChecking ||
1141 ice_connection_state_ ==
1142 PeerConnectionInterface::kIceConnectionDisconnected) {
1143 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
1144 }
1145 } else if (transport->HasChannels()) {
1146 // If the current state is Connected or Completed, then there were writable
1147 // channels but now there are not, so the next state must be Disconnected.
1148 if (ice_connection_state_ ==
1149 PeerConnectionInterface::kIceConnectionConnected ||
1150 ice_connection_state_ ==
1151 PeerConnectionInterface::kIceConnectionCompleted) {
1152 SetIceConnectionState(
1153 PeerConnectionInterface::kIceConnectionDisconnected);
1154 }
1155 }
1156}
1157
1158void WebRtcSession::OnTransportProxyCandidatesReady(
1159 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1160 ASSERT(signaling_thread()->IsCurrent());
1161 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1162}
1163
1164bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1165 return ((action == kOffer && state() == STATE_INIT) ||
1166 // update local offer
1167 (action == kOffer && state() == STATE_SENTINITIATE) ||
1168 // update the current ongoing session.
1169 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1170 (action == kOffer && state() == STATE_SENTACCEPT) ||
1171 (action == kOffer && state() == STATE_INPROGRESS) ||
1172 // accept remote offer
1173 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1174 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1175 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1176 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1177}
1178
1179bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1180 return ((action == kOffer && state() == STATE_INIT) ||
1181 // update remote offer
1182 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1183 // update the current ongoing session
1184 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1185 (action == kOffer && state() == STATE_SENTACCEPT) ||
1186 (action == kOffer && state() == STATE_INPROGRESS) ||
1187 // accept local offer
1188 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1189 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1190 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1191 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1192}
1193
1194void WebRtcSession::OnCandidatesAllocationDone() {
1195 ASSERT(signaling_thread()->IsCurrent());
1196 if (ice_observer_) {
1197 ice_observer_->OnIceGatheringChange(
1198 PeerConnectionInterface::kIceGatheringComplete);
1199 ice_observer_->OnIceComplete();
1200 }
1201}
1202
1203// Enabling voice and video channel.
1204void WebRtcSession::EnableChannels() {
1205 if (voice_channel_ && !voice_channel_->enabled())
1206 voice_channel_->Enable(true);
1207
1208 if (video_channel_ && !video_channel_->enabled())
1209 video_channel_->Enable(true);
1210
1211 if (data_channel_.get() && !data_channel_->enabled())
1212 data_channel_->Enable(true);
1213}
1214
1215void WebRtcSession::ProcessNewLocalCandidate(
1216 const std::string& content_name,
1217 const cricket::Candidates& candidates) {
1218 int sdp_mline_index;
1219 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1220 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1221 << content_name << " not found";
1222 return;
1223 }
1224
1225 for (cricket::Candidates::const_iterator citer = candidates.begin();
1226 citer != candidates.end(); ++citer) {
1227 // Use content_name as the candidate media id.
1228 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1229 if (ice_observer_) {
1230 ice_observer_->OnIceCandidate(&candidate);
1231 }
1232 if (local_desc_) {
1233 local_desc_->AddCandidate(&candidate);
1234 }
1235 }
1236}
1237
1238// Returns the media index for a local ice candidate given the content name.
1239bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1240 int* sdp_mline_index) {
1241 if (!BaseSession::local_description() || !sdp_mline_index)
1242 return false;
1243
1244 bool content_found = false;
1245 const ContentInfos& contents = BaseSession::local_description()->contents();
1246 for (size_t index = 0; index < contents.size(); ++index) {
1247 if (contents[index].name == content_name) {
1248 *sdp_mline_index = index;
1249 content_found = true;
1250 break;
1251 }
1252 }
1253 return content_found;
1254}
1255
1256bool WebRtcSession::UseCandidatesInSessionDescription(
1257 const SessionDescriptionInterface* remote_desc) {
1258 if (!remote_desc)
1259 return true;
1260 bool ret = true;
1261 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1262 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1263 for (size_t n = 0; n < candidates->count(); ++n) {
1264 ret = UseCandidate(candidates->at(n));
1265 if (!ret)
1266 break;
1267 }
1268 }
1269 return ret;
1270}
1271
1272bool WebRtcSession::UseCandidate(
1273 const IceCandidateInterface* candidate) {
1274
1275 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
1276 size_t remote_content_size =
1277 BaseSession::remote_description()->contents().size();
1278 if (mediacontent_index >= remote_content_size) {
1279 LOG(LS_ERROR)
1280 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1281 return false;
1282 }
1283
1284 cricket::ContentInfo content =
1285 BaseSession::remote_description()->contents()[mediacontent_index];
1286 std::vector<cricket::Candidate> candidates;
1287 candidates.push_back(candidate->candidate());
1288 // Invoking BaseSession method to handle remote candidates.
1289 std::string error;
1290 if (OnRemoteCandidates(content.name, candidates, &error)) {
1291 // Candidates successfully submitted for checking.
1292 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1293 ice_connection_state_ ==
1294 PeerConnectionInterface::kIceConnectionDisconnected) {
1295 // If state is New, then the session has just gotten its first remote ICE
1296 // candidates, so go to Checking.
1297 // If state is Disconnected, the session is re-using old candidates or
1298 // receiving additional ones, so go to Checking.
1299 // If state is Connected, stay Connected.
1300 // TODO(bemasc): If state is Connected, and the new candidates are for a
1301 // newly added transport, then the state actually _should_ move to
1302 // checking. Add a way to distinguish that case.
1303 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1304 }
1305 // TODO(bemasc): If state is Completed, go back to Connected.
1306 } else {
1307 LOG(LS_WARNING) << error;
1308 }
1309 return true;
1310}
1311
1312void WebRtcSession::RemoveUnusedChannelsAndTransports(
1313 const SessionDescription* desc) {
1314 const cricket::ContentInfo* voice_info =
1315 cricket::GetFirstAudioContent(desc);
1316 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1317 mediastream_signaling_->OnAudioChannelClose();
1318 SignalVoiceChannelDestroyed();
1319 const std::string content_name = voice_channel_->content_name();
1320 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
1321 DestroyTransportProxy(content_name);
1322 }
1323
1324 const cricket::ContentInfo* video_info =
1325 cricket::GetFirstVideoContent(desc);
1326 if ((!video_info || video_info->rejected) && video_channel_) {
1327 mediastream_signaling_->OnVideoChannelClose();
1328 SignalVideoChannelDestroyed();
1329 const std::string content_name = video_channel_->content_name();
1330 channel_manager_->DestroyVideoChannel(video_channel_.release());
1331 DestroyTransportProxy(content_name);
1332 }
1333
1334 const cricket::ContentInfo* data_info =
1335 cricket::GetFirstDataContent(desc);
1336 if ((!data_info || data_info->rejected) && data_channel_) {
1337 mediastream_signaling_->OnDataChannelClose();
1338 SignalDataChannelDestroyed();
1339 const std::string content_name = data_channel_->content_name();
1340 channel_manager_->DestroyDataChannel(data_channel_.release());
1341 DestroyTransportProxy(content_name);
1342 }
1343}
1344
1345bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
1346 // Disabling the BUNDLE flag in PortAllocator if offer disabled it.
1347 if (state() == STATE_INIT && !desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
1348 port_allocator()->set_flags(port_allocator()->flags() &
1349 ~cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1350 }
1351
1352 // Creating the media channels and transport proxies.
1353 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1354 if (voice && !voice->rejected && !voice_channel_) {
1355 if (!CreateVoiceChannel(desc)) {
1356 LOG(LS_ERROR) << "Failed to create voice channel.";
1357 return false;
1358 }
1359 }
1360
1361 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1362 if (video && !video->rejected && !video_channel_) {
1363 if (!CreateVideoChannel(desc)) {
1364 LOG(LS_ERROR) << "Failed to create video channel.";
1365 return false;
1366 }
1367 }
1368
1369 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1370 if (data_channel_type_ != cricket::DCT_NONE &&
1371 data && !data->rejected && !data_channel_.get()) {
1372 if (!CreateDataChannel(desc)) {
1373 LOG(LS_ERROR) << "Failed to create data channel.";
1374 return false;
1375 }
1376 }
1377
1378 return true;
1379}
1380
1381bool WebRtcSession::CreateVoiceChannel(const SessionDescription* desc) {
1382 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1383 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
1384 this, voice->name, true));
1385 return voice_channel_ ? true : false;
1386}
1387
1388bool WebRtcSession::CreateVideoChannel(const SessionDescription* desc) {
1389 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1390 video_channel_.reset(channel_manager_->CreateVideoChannel(
1391 this, video->name, true, voice_channel_.get()));
1392 return video_channel_ ? true : false;
1393}
1394
1395bool WebRtcSession::CreateDataChannel(const SessionDescription* desc) {
1396 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1397 bool rtcp = (data_channel_type_ == cricket::DCT_RTP);
1398 data_channel_.reset(channel_manager_->CreateDataChannel(
1399 this, data->name, rtcp, data_channel_type_));
1400 if (!data_channel_.get()) {
1401 return false;
1402 }
1403 return true;
1404}
1405
1406void WebRtcSession::CopySavedCandidates(
1407 SessionDescriptionInterface* dest_desc) {
1408 if (!dest_desc) {
1409 ASSERT(false);
1410 return;
1411 }
1412 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1413 dest_desc->AddCandidate(saved_candidates_[i]);
1414 delete saved_candidates_[i];
1415 }
1416 saved_candidates_.clear();
1417}
1418
1419void WebRtcSession::UpdateSessionDescriptionSecurePolicy(
1420 SessionDescription* sdesc) {
1421 if (!sdesc) {
1422 return;
1423 }
1424
1425 // Updating the |crypto_required_| in MediaContentDescription to the
1426 // appropriate state based on the current security policy.
1427 for (cricket::ContentInfos::iterator iter = sdesc->contents().begin();
1428 iter != sdesc->contents().end(); ++iter) {
1429 if (cricket::IsMediaContent(&*iter)) {
1430 MediaContentDescription* mdesc =
1431 static_cast<MediaContentDescription*> (iter->description);
1432 if (mdesc) {
1433 mdesc->set_crypto_required(
1434 session_desc_factory_.secure() == cricket::SEC_REQUIRED);
1435 }
1436 }
1437 }
1438}
1439
1440} // namespace webrtc