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