blob: 840cb3d7ad9146d266044c24f13749b47cbcb9c5 [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) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000632 // Takes the ownership of |desc| regardless of the result.
633 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
634
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000635 if (error() != cricket::BaseSession::ERROR_NONE) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000636 return BadLocalSdp(SessionErrorMsg(error()), err_desc);
637 }
638
639 if (!desc || !desc->description()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000640 return BadLocalSdp(kInvalidSdp, err_desc);
641 }
642 Action action = GetAction(desc->type());
643 if (!ExpectSetLocalDescription(action)) {
644 std::string type = desc->type();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000645 return BadLocalSdp(BadStateErrMsg(type, state()), err_desc);
646 }
647
648 if (session_desc_factory_.secure() == cricket::SEC_REQUIRED &&
649 !VerifyCrypto(desc->description())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000650 return BadLocalSdp(kSdpWithoutCrypto, err_desc);
651 }
652
653 if (action == kAnswer && !VerifyMediaDescriptions(
654 desc->description(), remote_description()->description())) {
655 return BadLocalSdp(kMlineMismatch, err_desc);
656 }
657
658 // Update the initiator flag if this session is the initiator.
659 if (state() == STATE_INIT && action == kOffer) {
660 set_initiator(true);
661 }
662
663 // Update the MediaContentDescription crypto settings as per the policy set.
664 UpdateSessionDescriptionSecurePolicy(desc->description());
665
666 set_local_description(desc->description()->Copy());
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000667 local_desc_.reset(desc_temp.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000668
669 // Transport and Media channels will be created only when offer is set.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000670 if (action == kOffer && !CreateChannels(local_desc_->description())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000671 // TODO(mallinath) - Handle CreateChannel failure, as new local description
672 // is applied. Restore back to old description.
673 return BadLocalSdp(kCreateChannelFailed, err_desc);
674 }
675
676 // Remove channel and transport proxies, if MediaContentDescription is
677 // rejected.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000678 RemoveUnusedChannelsAndTransports(local_desc_->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000679
680 if (!UpdateSessionState(action, cricket::CS_LOCAL,
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000681 local_desc_->description(), err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682 return false;
683 }
684 // Kick starting the ice candidates allocation.
685 StartCandidatesAllocation();
686
687 // Update state and SSRC of local MediaStreams and DataChannels based on the
688 // local session description.
689 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
690
691 if (error() != cricket::BaseSession::ERROR_NONE) {
692 return BadLocalSdp(SessionErrorMsg(error()), err_desc);
693 }
694 return true;
695}
696
697bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
698 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000699 // Takes the ownership of |desc| regardless of the result.
700 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
701
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000702 if (error() != cricket::BaseSession::ERROR_NONE) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000703 return BadRemoteSdp(SessionErrorMsg(error()), err_desc);
704 }
705
706 if (!desc || !desc->description()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707 return BadRemoteSdp(kInvalidSdp, err_desc);
708 }
709 Action action = GetAction(desc->type());
710 if (!ExpectSetRemoteDescription(action)) {
711 std::string type = desc->type();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000712 return BadRemoteSdp(BadStateErrMsg(type, state()), err_desc);
713 }
714
715 if (action == kAnswer && !VerifyMediaDescriptions(
716 desc->description(), local_description()->description())) {
717 return BadRemoteSdp(kMlineMismatch, err_desc);
718 }
719
720 if (session_desc_factory_.secure() == cricket::SEC_REQUIRED &&
721 !VerifyCrypto(desc->description())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 return BadRemoteSdp(kSdpWithoutCrypto, err_desc);
723 }
724
725 // Transport and Media channels will be created only when offer is set.
726 if (action == kOffer && !CreateChannels(desc->description())) {
727 // TODO(mallinath) - Handle CreateChannel failure, as new local description
728 // is applied. Restore back to old description.
729 return BadRemoteSdp(kCreateChannelFailed, err_desc);
730 }
731
732 // Remove channel and transport proxies, if MediaContentDescription is
733 // rejected.
734 RemoveUnusedChannelsAndTransports(desc->description());
735
736 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
737 // is called.
738 set_remote_description(desc->description()->Copy());
739 if (!UpdateSessionState(action, cricket::CS_REMOTE,
740 desc->description(), err_desc)) {
741 return false;
742 }
743
744 // Update remote MediaStreams.
745 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
746 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000747 return BadRemoteSdp(kInvalidCandidates, err_desc);
748 }
749
750 // Copy all saved candidates.
751 CopySavedCandidates(desc);
752 // We retain all received candidates.
753 CopyCandidatesFromSessionDescription(remote_desc_.get(), desc);
754 // Check if this new SessionDescription contains new ice ufrag and password
755 // that indicates the remote peer requests ice restart.
756 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(),
757 desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000758 remote_desc_.reset(desc_temp.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000759 if (error() != cricket::BaseSession::ERROR_NONE) {
760 return BadRemoteSdp(SessionErrorMsg(error()), err_desc);
761 }
762 return true;
763}
764
765bool WebRtcSession::UpdateSessionState(
766 Action action, cricket::ContentSource source,
767 const cricket::SessionDescription* desc,
768 std::string* err_desc) {
769 // If there's already a pending error then no state transition should happen.
770 // But all call-sites should be verifying this before calling us!
771 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
772 if (action == kOffer) {
773 if (!PushdownTransportDescription(source, cricket::CA_OFFER)) {
774 return BadSdp(source, kPushDownOfferTDFailed, err_desc);
775 }
776 SetState(source == cricket::CS_LOCAL ?
777 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
778 if (error() != cricket::BaseSession::ERROR_NONE) {
779 return SetSessionStateFailed(source, error(), err_desc);
780 }
781 } else if (action == kPrAnswer) {
782 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER)) {
783 return BadSdp(source, kPushDownPranswerTDFailed, err_desc);
784 }
785 EnableChannels();
786 SetState(source == cricket::CS_LOCAL ?
787 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
788 if (error() != cricket::BaseSession::ERROR_NONE) {
789 return SetSessionStateFailed(source, error(), err_desc);
790 }
791 } else if (action == kAnswer) {
792 if (!PushdownTransportDescription(source, cricket::CA_ANSWER)) {
793 return BadSdp(source, kPushDownAnswerTDFailed, err_desc);
794 }
795 MaybeEnableMuxingSupport();
796 EnableChannels();
797 SetState(source == cricket::CS_LOCAL ?
798 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
799 if (error() != cricket::BaseSession::ERROR_NONE) {
800 return SetSessionStateFailed(source, error(), err_desc);
801 }
802 }
803 return true;
804}
805
806WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
807 if (type == SessionDescriptionInterface::kOffer) {
808 return WebRtcSession::kOffer;
809 } else if (type == SessionDescriptionInterface::kPrAnswer) {
810 return WebRtcSession::kPrAnswer;
811 } else if (type == SessionDescriptionInterface::kAnswer) {
812 return WebRtcSession::kAnswer;
813 }
814 ASSERT(false && "unknown action type");
815 return WebRtcSession::kOffer;
816}
817
818bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
819 if (state() == STATE_INIT) {
820 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
821 << "without any offer (local or remote) "
822 << "session description.";
823 return false;
824 }
825
826 if (!candidate) {
827 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
828 return false;
829 }
830
831 if (!local_description() || !remote_description()) {
832 LOG(LS_INFO) << "ProcessIceMessage: Remote description not set, "
833 << "save the candidate for later use.";
834 saved_candidates_.push_back(
835 new JsepIceCandidate(candidate->sdp_mid(), candidate->sdp_mline_index(),
836 candidate->candidate()));
837 return true;
838 }
839
840 // Add this candidate to the remote session description.
841 if (!remote_desc_->AddCandidate(candidate)) {
842 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
843 return false;
844 }
845
846 return UseCandidatesInSessionDescription(remote_desc_.get());
847}
848
849bool WebRtcSession::GetTrackIdBySsrc(uint32 ssrc, std::string* id) {
850 if (GetLocalTrackId(ssrc, id)) {
851 if (GetRemoteTrackId(ssrc, id)) {
852 LOG(LS_WARNING) << "SSRC " << ssrc
853 << " exists in both local and remote descriptions";
854 return true; // We return the remote track id.
855 }
856 return true;
857 } else {
858 return GetRemoteTrackId(ssrc, id);
859 }
860}
861
862bool WebRtcSession::GetLocalTrackId(uint32 ssrc, std::string* track_id) {
863 if (!BaseSession::local_description())
864 return false;
865 return webrtc::GetTrackIdBySsrc(
866 BaseSession::local_description(), ssrc, track_id);
867}
868
869bool WebRtcSession::GetRemoteTrackId(uint32 ssrc, std::string* track_id) {
870 if (!BaseSession::remote_description())
871 return false;
872 return webrtc::GetTrackIdBySsrc(
873 BaseSession::remote_description(), ssrc, track_id);
874}
875
876std::string WebRtcSession::BadStateErrMsg(
877 const std::string& type, State state) {
878 std::ostringstream desc;
879 desc << "Called with type in wrong state, "
880 << "type: " << type << " state: " << GetStateString(state);
881 return desc.str();
882}
883
884void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable) {
885 ASSERT(signaling_thread()->IsCurrent());
886 if (!voice_channel_) {
887 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
888 return;
889 }
890 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
891 // Allow that SetOutputScaling fail if |enable| is false but assert
892 // otherwise. This in the normal case when the underlying media channel has
893 // already been deleted.
894 ASSERT(enable == false);
895 }
896}
897
898void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
899 const cricket::AudioOptions& options) {
900 ASSERT(signaling_thread()->IsCurrent());
901 if (!voice_channel_) {
902 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
903 return;
904 }
905 if (!voice_channel_->MuteStream(ssrc, !enable)) {
906 // Allow that MuteStream fail if |enable| is false but assert otherwise.
907 // This in the normal case when the underlying media channel has already
908 // been deleted.
909 ASSERT(enable == false);
910 return;
911 }
912 if (enable)
913 voice_channel_->SetChannelOptions(options);
914}
915
916bool WebRtcSession::SetAudioRenderer(uint32 ssrc,
917 cricket::AudioRenderer* renderer) {
918 if (!voice_channel_) {
919 LOG(LS_ERROR) << "SetAudioRenderer: No audio channel exists.";
920 return false;
921 }
922
923 if (!voice_channel_->SetRenderer(ssrc, renderer)) {
924 // SetRenderer() can fail if the ssrc is not mapping to the playout channel.
925 LOG(LS_ERROR) << "SetAudioRenderer: ssrc is incorrect: " << ssrc;
926 return false;
927 }
928
929 return true;
930}
931
932bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
933 cricket::VideoCapturer* camera) {
934 ASSERT(signaling_thread()->IsCurrent());
935
936 if (!video_channel_.get()) {
937 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
938 // support video.
939 LOG(LS_WARNING) << "Video not used in this call.";
940 return false;
941 }
942 if (!video_channel_->SetCapturer(ssrc, camera)) {
943 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
944 // This in the normal case when the underlying media channel has already
945 // been deleted.
946 ASSERT(camera == NULL);
947 return false;
948 }
949 return true;
950}
951
952void WebRtcSession::SetVideoPlayout(uint32 ssrc,
953 bool enable,
954 cricket::VideoRenderer* renderer) {
955 ASSERT(signaling_thread()->IsCurrent());
956 if (!video_channel_) {
957 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
958 return;
959 }
960 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
961 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
962 // This in the normal case when the underlying media channel has already
963 // been deleted.
964 ASSERT(renderer == NULL);
965 }
966}
967
968void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
969 const cricket::VideoOptions* options) {
970 ASSERT(signaling_thread()->IsCurrent());
971 if (!video_channel_) {
972 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
973 return;
974 }
975 if (!video_channel_->MuteStream(ssrc, !enable)) {
976 // Allow that MuteStream fail if |enable| is false but assert otherwise.
977 // This in the normal case when the underlying media channel has already
978 // been deleted.
979 ASSERT(enable == false);
980 return;
981 }
982 if (enable && options)
983 video_channel_->SetChannelOptions(*options);
984}
985
986bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
987 ASSERT(signaling_thread()->IsCurrent());
988 if (!voice_channel_) {
989 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
990 return false;
991 }
992 uint32 send_ssrc = 0;
993 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
994 // exists.
995 if (!GetAudioSsrcByTrackId(BaseSession::local_description(), track_id,
996 &send_ssrc)) {
997 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
998 return false;
999 }
1000 return voice_channel_->CanInsertDtmf();
1001}
1002
1003bool WebRtcSession::InsertDtmf(const std::string& track_id,
1004 int code, int duration) {
1005 ASSERT(signaling_thread()->IsCurrent());
1006 if (!voice_channel_) {
1007 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1008 return false;
1009 }
1010 uint32 send_ssrc = 0;
1011 if (!VERIFY(GetAudioSsrcByTrackId(BaseSession::local_description(),
1012 track_id, &send_ssrc))) {
1013 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1014 return false;
1015 }
1016 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1017 cricket::DF_SEND)) {
1018 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1019 return false;
1020 }
1021 return true;
1022}
1023
1024sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1025 return &SignalVoiceChannelDestroyed;
1026}
1027
1028talk_base::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
1029 const std::string& label,
1030 const DataChannelInit* config) {
1031 if (state() == STATE_RECEIVEDTERMINATE) {
1032 return NULL;
1033 }
1034 if (data_channel_type_ == cricket::DCT_NONE) {
1035 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1036 return NULL;
1037 }
1038 DataChannelInit new_config = config ? (*config) : DataChannelInit();
1039
1040 if (data_channel_type_ == cricket::DCT_SCTP) {
1041 if (new_config.id < 0) {
1042 if (!mediastream_signaling_->AllocateSctpId(&new_config.id)) {
1043 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1044 return NULL;
1045 }
1046 } else if (!mediastream_signaling_->IsSctpIdAvailable(new_config.id)) {
1047 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1048 << "because the id is already in use or out of range.";
1049 return NULL;
1050 }
1051 }
1052 talk_base::scoped_refptr<DataChannel> channel(
1053 DataChannel::Create(this, label, &new_config));
1054 if (channel == NULL)
1055 return NULL;
1056 if (!mediastream_signaling_->AddDataChannel(channel))
1057 return NULL;
1058 return channel;
1059}
1060
1061cricket::DataChannelType WebRtcSession::data_channel_type() const {
1062 return data_channel_type_;
1063}
1064
1065void WebRtcSession::SetIceConnectionState(
1066 PeerConnectionInterface::IceConnectionState state) {
1067 if (ice_connection_state_ == state) {
1068 return;
1069 }
1070
1071 // ASSERT that the requested transition is allowed. Note that
1072 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1073 // within PeerConnection). This switch statement should compile away when
1074 // ASSERTs are disabled.
1075 switch (ice_connection_state_) {
1076 case PeerConnectionInterface::kIceConnectionNew:
1077 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1078 break;
1079 case PeerConnectionInterface::kIceConnectionChecking:
1080 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1081 state == PeerConnectionInterface::kIceConnectionConnected);
1082 break;
1083 case PeerConnectionInterface::kIceConnectionConnected:
1084 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1085 state == PeerConnectionInterface::kIceConnectionChecking ||
1086 state == PeerConnectionInterface::kIceConnectionCompleted);
1087 break;
1088 case PeerConnectionInterface::kIceConnectionCompleted:
1089 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1090 state == PeerConnectionInterface::kIceConnectionDisconnected);
1091 break;
1092 case PeerConnectionInterface::kIceConnectionFailed:
1093 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1094 break;
1095 case PeerConnectionInterface::kIceConnectionDisconnected:
1096 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1097 state == PeerConnectionInterface::kIceConnectionConnected ||
1098 state == PeerConnectionInterface::kIceConnectionCompleted ||
1099 state == PeerConnectionInterface::kIceConnectionFailed);
1100 break;
1101 case PeerConnectionInterface::kIceConnectionClosed:
1102 ASSERT(false);
1103 break;
1104 default:
1105 ASSERT(false);
1106 break;
1107 }
1108
1109 ice_connection_state_ = state;
1110 if (ice_observer_) {
1111 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1112 }
1113}
1114
1115void WebRtcSession::OnTransportRequestSignaling(
1116 cricket::Transport* transport) {
1117 ASSERT(signaling_thread()->IsCurrent());
1118 transport->OnSignalingReady();
1119 if (ice_observer_) {
1120 ice_observer_->OnIceGatheringChange(
1121 PeerConnectionInterface::kIceGatheringGathering);
1122 }
1123}
1124
1125void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1126 ASSERT(signaling_thread()->IsCurrent());
1127 // start monitoring for the write state of the transport.
1128 OnTransportWritable(transport);
1129}
1130
1131void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1132 ASSERT(signaling_thread()->IsCurrent());
1133 // TODO(bemasc): Expose more API from Transport to detect when
1134 // candidate selection starts or stops, due to success or failure.
1135 if (transport->all_channels_writable()) {
1136 if (ice_connection_state_ ==
1137 PeerConnectionInterface::kIceConnectionChecking ||
1138 ice_connection_state_ ==
1139 PeerConnectionInterface::kIceConnectionDisconnected) {
1140 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
1141 }
1142 } else if (transport->HasChannels()) {
1143 // If the current state is Connected or Completed, then there were writable
1144 // channels but now there are not, so the next state must be Disconnected.
1145 if (ice_connection_state_ ==
1146 PeerConnectionInterface::kIceConnectionConnected ||
1147 ice_connection_state_ ==
1148 PeerConnectionInterface::kIceConnectionCompleted) {
1149 SetIceConnectionState(
1150 PeerConnectionInterface::kIceConnectionDisconnected);
1151 }
1152 }
1153}
1154
1155void WebRtcSession::OnTransportProxyCandidatesReady(
1156 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1157 ASSERT(signaling_thread()->IsCurrent());
1158 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1159}
1160
1161bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1162 return ((action == kOffer && state() == STATE_INIT) ||
1163 // update local offer
1164 (action == kOffer && state() == STATE_SENTINITIATE) ||
1165 // update the current ongoing session.
1166 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1167 (action == kOffer && state() == STATE_SENTACCEPT) ||
1168 (action == kOffer && state() == STATE_INPROGRESS) ||
1169 // accept remote offer
1170 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1171 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1172 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1173 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1174}
1175
1176bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1177 return ((action == kOffer && state() == STATE_INIT) ||
1178 // update remote offer
1179 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1180 // update the current ongoing session
1181 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1182 (action == kOffer && state() == STATE_SENTACCEPT) ||
1183 (action == kOffer && state() == STATE_INPROGRESS) ||
1184 // accept local offer
1185 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1186 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1187 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1188 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1189}
1190
1191void WebRtcSession::OnCandidatesAllocationDone() {
1192 ASSERT(signaling_thread()->IsCurrent());
1193 if (ice_observer_) {
1194 ice_observer_->OnIceGatheringChange(
1195 PeerConnectionInterface::kIceGatheringComplete);
1196 ice_observer_->OnIceComplete();
1197 }
1198}
1199
1200// Enabling voice and video channel.
1201void WebRtcSession::EnableChannels() {
1202 if (voice_channel_ && !voice_channel_->enabled())
1203 voice_channel_->Enable(true);
1204
1205 if (video_channel_ && !video_channel_->enabled())
1206 video_channel_->Enable(true);
1207
1208 if (data_channel_.get() && !data_channel_->enabled())
1209 data_channel_->Enable(true);
1210}
1211
1212void WebRtcSession::ProcessNewLocalCandidate(
1213 const std::string& content_name,
1214 const cricket::Candidates& candidates) {
1215 int sdp_mline_index;
1216 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1217 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1218 << content_name << " not found";
1219 return;
1220 }
1221
1222 for (cricket::Candidates::const_iterator citer = candidates.begin();
1223 citer != candidates.end(); ++citer) {
1224 // Use content_name as the candidate media id.
1225 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1226 if (ice_observer_) {
1227 ice_observer_->OnIceCandidate(&candidate);
1228 }
1229 if (local_desc_) {
1230 local_desc_->AddCandidate(&candidate);
1231 }
1232 }
1233}
1234
1235// Returns the media index for a local ice candidate given the content name.
1236bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1237 int* sdp_mline_index) {
1238 if (!BaseSession::local_description() || !sdp_mline_index)
1239 return false;
1240
1241 bool content_found = false;
1242 const ContentInfos& contents = BaseSession::local_description()->contents();
1243 for (size_t index = 0; index < contents.size(); ++index) {
1244 if (contents[index].name == content_name) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001245 *sdp_mline_index = static_cast<int>(index);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001246 content_found = true;
1247 break;
1248 }
1249 }
1250 return content_found;
1251}
1252
1253bool WebRtcSession::UseCandidatesInSessionDescription(
1254 const SessionDescriptionInterface* remote_desc) {
1255 if (!remote_desc)
1256 return true;
1257 bool ret = true;
1258 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1259 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1260 for (size_t n = 0; n < candidates->count(); ++n) {
1261 ret = UseCandidate(candidates->at(n));
1262 if (!ret)
1263 break;
1264 }
1265 }
1266 return ret;
1267}
1268
1269bool WebRtcSession::UseCandidate(
1270 const IceCandidateInterface* candidate) {
1271
1272 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
1273 size_t remote_content_size =
1274 BaseSession::remote_description()->contents().size();
1275 if (mediacontent_index >= remote_content_size) {
1276 LOG(LS_ERROR)
1277 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1278 return false;
1279 }
1280
1281 cricket::ContentInfo content =
1282 BaseSession::remote_description()->contents()[mediacontent_index];
1283 std::vector<cricket::Candidate> candidates;
1284 candidates.push_back(candidate->candidate());
1285 // Invoking BaseSession method to handle remote candidates.
1286 std::string error;
1287 if (OnRemoteCandidates(content.name, candidates, &error)) {
1288 // Candidates successfully submitted for checking.
1289 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1290 ice_connection_state_ ==
1291 PeerConnectionInterface::kIceConnectionDisconnected) {
1292 // If state is New, then the session has just gotten its first remote ICE
1293 // candidates, so go to Checking.
1294 // If state is Disconnected, the session is re-using old candidates or
1295 // receiving additional ones, so go to Checking.
1296 // If state is Connected, stay Connected.
1297 // TODO(bemasc): If state is Connected, and the new candidates are for a
1298 // newly added transport, then the state actually _should_ move to
1299 // checking. Add a way to distinguish that case.
1300 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1301 }
1302 // TODO(bemasc): If state is Completed, go back to Connected.
1303 } else {
1304 LOG(LS_WARNING) << error;
1305 }
1306 return true;
1307}
1308
1309void WebRtcSession::RemoveUnusedChannelsAndTransports(
1310 const SessionDescription* desc) {
1311 const cricket::ContentInfo* voice_info =
1312 cricket::GetFirstAudioContent(desc);
1313 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1314 mediastream_signaling_->OnAudioChannelClose();
1315 SignalVoiceChannelDestroyed();
1316 const std::string content_name = voice_channel_->content_name();
1317 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
1318 DestroyTransportProxy(content_name);
1319 }
1320
1321 const cricket::ContentInfo* video_info =
1322 cricket::GetFirstVideoContent(desc);
1323 if ((!video_info || video_info->rejected) && video_channel_) {
1324 mediastream_signaling_->OnVideoChannelClose();
1325 SignalVideoChannelDestroyed();
1326 const std::string content_name = video_channel_->content_name();
1327 channel_manager_->DestroyVideoChannel(video_channel_.release());
1328 DestroyTransportProxy(content_name);
1329 }
1330
1331 const cricket::ContentInfo* data_info =
1332 cricket::GetFirstDataContent(desc);
1333 if ((!data_info || data_info->rejected) && data_channel_) {
1334 mediastream_signaling_->OnDataChannelClose();
1335 SignalDataChannelDestroyed();
1336 const std::string content_name = data_channel_->content_name();
1337 channel_manager_->DestroyDataChannel(data_channel_.release());
1338 DestroyTransportProxy(content_name);
1339 }
1340}
1341
1342bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
1343 // Disabling the BUNDLE flag in PortAllocator if offer disabled it.
1344 if (state() == STATE_INIT && !desc->HasGroup(cricket::GROUP_TYPE_BUNDLE)) {
1345 port_allocator()->set_flags(port_allocator()->flags() &
1346 ~cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1347 }
1348
1349 // Creating the media channels and transport proxies.
1350 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1351 if (voice && !voice->rejected && !voice_channel_) {
1352 if (!CreateVoiceChannel(desc)) {
1353 LOG(LS_ERROR) << "Failed to create voice channel.";
1354 return false;
1355 }
1356 }
1357
1358 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1359 if (video && !video->rejected && !video_channel_) {
1360 if (!CreateVideoChannel(desc)) {
1361 LOG(LS_ERROR) << "Failed to create video channel.";
1362 return false;
1363 }
1364 }
1365
1366 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1367 if (data_channel_type_ != cricket::DCT_NONE &&
1368 data && !data->rejected && !data_channel_.get()) {
1369 if (!CreateDataChannel(desc)) {
1370 LOG(LS_ERROR) << "Failed to create data channel.";
1371 return false;
1372 }
1373 }
1374
1375 return true;
1376}
1377
1378bool WebRtcSession::CreateVoiceChannel(const SessionDescription* desc) {
1379 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1380 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
1381 this, voice->name, true));
1382 return voice_channel_ ? true : false;
1383}
1384
1385bool WebRtcSession::CreateVideoChannel(const SessionDescription* desc) {
1386 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1387 video_channel_.reset(channel_manager_->CreateVideoChannel(
1388 this, video->name, true, voice_channel_.get()));
1389 return video_channel_ ? true : false;
1390}
1391
1392bool WebRtcSession::CreateDataChannel(const SessionDescription* desc) {
1393 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1394 bool rtcp = (data_channel_type_ == cricket::DCT_RTP);
1395 data_channel_.reset(channel_manager_->CreateDataChannel(
1396 this, data->name, rtcp, data_channel_type_));
1397 if (!data_channel_.get()) {
1398 return false;
1399 }
1400 return true;
1401}
1402
1403void WebRtcSession::CopySavedCandidates(
1404 SessionDescriptionInterface* dest_desc) {
1405 if (!dest_desc) {
1406 ASSERT(false);
1407 return;
1408 }
1409 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1410 dest_desc->AddCandidate(saved_candidates_[i]);
1411 delete saved_candidates_[i];
1412 }
1413 saved_candidates_.clear();
1414}
1415
1416void WebRtcSession::UpdateSessionDescriptionSecurePolicy(
1417 SessionDescription* sdesc) {
1418 if (!sdesc) {
1419 return;
1420 }
1421
1422 // Updating the |crypto_required_| in MediaContentDescription to the
1423 // appropriate state based on the current security policy.
1424 for (cricket::ContentInfos::iterator iter = sdesc->contents().begin();
1425 iter != sdesc->contents().end(); ++iter) {
1426 if (cricket::IsMediaContent(&*iter)) {
1427 MediaContentDescription* mdesc =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001428 static_cast<MediaContentDescription*>(iter->description);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001429 if (mdesc) {
1430 mdesc->set_crypto_required(
1431 session_desc_factory_.secure() == cricket::SEC_REQUIRED);
1432 }
1433 }
1434 }
1435}
1436
1437} // namespace webrtc