blob: 63aca36449ede4b0754559f734f69af8f0da78cf [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
pbos@webrtc.org371243d2014-03-07 15:22:04 +000030#include <limits.h>
31
henrike@webrtc.org28e20752013-07-10 00:45:36 +000032#include <algorithm>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000033#include <vector>
34
35#include "talk/app/webrtc/jsepicecandidate.h"
36#include "talk/app/webrtc/jsepsessiondescription.h"
37#include "talk/app/webrtc/mediaconstraintsinterface.h"
38#include "talk/app/webrtc/mediastreamsignaling.h"
39#include "talk/app/webrtc/peerconnectioninterface.h"
wu@webrtc.org91053e72013-08-10 07:18:04 +000040#include "talk/app/webrtc/webrtcsessiondescriptionfactory.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000041#include "talk/base/helpers.h"
42#include "talk/base/logging.h"
43#include "talk/base/stringencode.h"
44#include "talk/media/base/constants.h"
45#include "talk/media/base/videocapturer.h"
46#include "talk/session/media/channel.h"
47#include "talk/session/media/channelmanager.h"
48#include "talk/session/media/mediasession.h"
49
50using cricket::ContentInfo;
51using cricket::ContentInfos;
52using cricket::MediaContentDescription;
53using cricket::SessionDescription;
54using cricket::TransportInfo;
55
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056namespace webrtc {
57
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058// Error messages
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000059const char kBundleWithoutRtcpMux[] = "RTCP-MUX must be enabled when BUNDLE "
60 "is enabled.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000061const char kCreateChannelFailed[] = "Failed to create channels.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062const char kInvalidCandidates[] = "Description contains invalid candidates.";
63const char kInvalidSdp[] = "Invalid session description.";
64const char kMlineMismatch[] =
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000065 "Offer and answer descriptions m-lines are not matching. Rejecting answer.";
66const char kPushDownTDFailed[] =
67 "Failed to push down transport description:";
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +000068const char kSdpWithoutDtlsFingerprint[] =
69 "Called with SDP without DTLS fingerprint.";
70const char kSdpWithoutSdesCrypto[] =
71 "Called with SDP without SDES crypto.";
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +000072const char kSdpWithoutIceUfragPwd[] =
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +000073 "Called with SDP without ice-ufrag and ice-pwd.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074const char kSessionError[] = "Session error code: ";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000075const char kSessionErrorDesc[] = "Session error description: ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000076
77// Compares |answer| against |offer|. Comparision is done
78// for number of m-lines in answer against offer. If matches true will be
79// returned otherwise false.
80static bool VerifyMediaDescriptions(
81 const SessionDescription* answer, const SessionDescription* offer) {
82 if (offer->contents().size() != answer->contents().size())
83 return false;
84
85 for (size_t i = 0; i < offer->contents().size(); ++i) {
86 if ((offer->contents()[i].name) != answer->contents()[i].name) {
87 return false;
88 }
wu@webrtc.org4e393072014-04-07 17:04:35 +000089 const MediaContentDescription* offer_mdesc =
90 static_cast<const MediaContentDescription*>(
91 offer->contents()[i].description);
92 const MediaContentDescription* answer_mdesc =
93 static_cast<const MediaContentDescription*>(
94 answer->contents()[i].description);
95 if (offer_mdesc->type() != answer_mdesc->type()) {
96 return false;
97 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +000098 }
99 return true;
100}
101
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102// Checks that each non-rejected content has SDES crypto keys or a DTLS
103// fingerprint. Mismatches, such as replying with a DTLS fingerprint to SDES
104// keys, will be caught in Transport negotiation, and backstopped by Channel's
105// |secure_required| check.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000106static bool VerifyCrypto(const SessionDescription* desc,
107 bool dtls_enabled,
108 std::string* error) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109 const ContentInfos& contents = desc->contents();
110 for (size_t index = 0; index < contents.size(); ++index) {
111 const ContentInfo* cinfo = &contents[index];
112 if (cinfo->rejected) {
113 continue;
114 }
115
116 // If the content isn't rejected, crypto must be present.
117 const MediaContentDescription* media =
118 static_cast<const MediaContentDescription*>(cinfo->description);
119 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
120 if (!media || !tinfo) {
121 // Something is not right.
122 LOG(LS_ERROR) << kInvalidSdp;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000123 *error = kInvalidSdp;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000124 return false;
125 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000126 if (dtls_enabled) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000127 if (!tinfo->description.identity_fingerprint) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000128 LOG(LS_WARNING) <<
129 "Session description must have DTLS fingerprint if DTLS enabled.";
130 *error = kSdpWithoutDtlsFingerprint;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000131 return false;
132 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000133 } else {
134 if (media->cryptos().empty()) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000135 LOG(LS_WARNING) <<
136 "Session description must have SDES when DTLS disabled.";
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000137 *error = kSdpWithoutSdesCrypto;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000138 return false;
139 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000140 }
141 }
142
143 return true;
144}
145
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +0000146// Checks that each non-rejected content has ice-ufrag and ice-pwd set.
147static bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
148 const ContentInfos& contents = desc->contents();
149 for (size_t index = 0; index < contents.size(); ++index) {
150 const ContentInfo* cinfo = &contents[index];
151 if (cinfo->rejected) {
152 continue;
153 }
154
155 // If the content isn't rejected, ice-ufrag and ice-pwd must be present.
156 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
157 if (!tinfo) {
158 // Something is not right.
159 LOG(LS_ERROR) << kInvalidSdp;
160 return false;
161 }
162 if (tinfo->description.ice_ufrag.empty() ||
163 tinfo->description.ice_pwd.empty()) {
164 LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
165 return false;
166 }
167 }
168 return true;
169}
170
wu@webrtc.org91053e72013-08-10 07:18:04 +0000171// Forces |sdesc->crypto_required| to the appropriate state based on the
172// current security policy, to ensure a failure occurs if there is an error
173// in crypto negotiation.
174// Called when processing the local session description.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000175static void UpdateSessionDescriptionSecurePolicy(cricket::CryptoType type,
176 SessionDescription* sdesc) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000177 if (!sdesc) {
178 return;
179 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000180
wu@webrtc.org91053e72013-08-10 07:18:04 +0000181 // Updating the |crypto_required_| in MediaContentDescription to the
182 // appropriate state based on the current security policy.
183 for (cricket::ContentInfos::iterator iter = sdesc->contents().begin();
184 iter != sdesc->contents().end(); ++iter) {
185 if (cricket::IsMediaContent(&*iter)) {
186 MediaContentDescription* mdesc =
187 static_cast<MediaContentDescription*> (iter->description);
188 if (mdesc) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000189 mdesc->set_crypto_required(type);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000190 }
191 }
192 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000193}
194
195static bool GetAudioSsrcByTrackId(
196 const SessionDescription* session_description,
197 const std::string& track_id, uint32 *ssrc) {
198 const cricket::ContentInfo* audio_info =
199 cricket::GetFirstAudioContent(session_description);
200 if (!audio_info) {
201 LOG(LS_ERROR) << "Audio not used in this call";
202 return false;
203 }
204
205 const cricket::MediaContentDescription* audio_content =
206 static_cast<const cricket::MediaContentDescription*>(
207 audio_info->description);
208 cricket::StreamParams stream;
209 if (!cricket::GetStreamByIds(audio_content->streams(), "", track_id,
210 &stream)) {
211 return false;
212 }
213 *ssrc = stream.first_ssrc();
214 return true;
215}
216
217static bool GetTrackIdBySsrc(const SessionDescription* session_description,
218 uint32 ssrc, std::string* track_id) {
219 ASSERT(track_id != NULL);
220
221 cricket::StreamParams stream_out;
222 const cricket::ContentInfo* audio_info =
223 cricket::GetFirstAudioContent(session_description);
224 if (!audio_info) {
225 return false;
226 }
227 const cricket::MediaContentDescription* audio_content =
228 static_cast<const cricket::MediaContentDescription*>(
229 audio_info->description);
230
231 if (cricket::GetStreamBySsrc(audio_content->streams(), ssrc, &stream_out)) {
232 *track_id = stream_out.id;
233 return true;
234 }
235
236 const cricket::ContentInfo* video_info =
237 cricket::GetFirstVideoContent(session_description);
238 if (!video_info) {
239 return false;
240 }
241 const cricket::MediaContentDescription* video_content =
242 static_cast<const cricket::MediaContentDescription*>(
243 video_info->description);
244
245 if (cricket::GetStreamBySsrc(video_content->streams(), ssrc, &stream_out)) {
246 *track_id = stream_out.id;
247 return true;
248 }
249 return false;
250}
251
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000252static bool BadSdp(const std::string& source,
253 const std::string& type,
254 const std::string& reason,
255 std::string* err_desc) {
256 std::ostringstream desc;
257 desc << "Failed to set " << source << " " << type << " sdp: " << reason;
258
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000259 if (err_desc) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000260 *err_desc = desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000261 }
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000262 LOG(LS_ERROR) << desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000263 return false;
264}
265
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000266static bool BadSdp(cricket::ContentSource source,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000267 const std::string& type,
268 const std::string& reason,
269 std::string* err_desc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000270 if (source == cricket::CS_LOCAL) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000271 return BadSdp("local", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000272 } else {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000273 return BadSdp("remote", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000274 }
275}
276
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000277static bool BadLocalSdp(const std::string& type,
278 const std::string& reason,
279 std::string* err_desc) {
280 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
281}
282
283static bool BadRemoteSdp(const std::string& type,
284 const std::string& reason,
285 std::string* err_desc) {
286 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
287}
288
289static bool BadOfferSdp(cricket::ContentSource source,
290 const std::string& reason,
291 std::string* err_desc) {
292 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
293}
294
295static bool BadPranswerSdp(cricket::ContentSource source,
296 const std::string& reason,
297 std::string* err_desc) {
298 return BadSdp(source, SessionDescriptionInterface::kPrAnswer,
299 reason, err_desc);
300}
301
302static bool BadAnswerSdp(cricket::ContentSource source,
303 const std::string& reason,
304 std::string* err_desc) {
305 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000306}
307
308#define GET_STRING_OF_STATE(state) \
309 case cricket::BaseSession::state: \
310 result = #state; \
311 break;
312
313static std::string GetStateString(cricket::BaseSession::State state) {
314 std::string result;
315 switch (state) {
316 GET_STRING_OF_STATE(STATE_INIT)
317 GET_STRING_OF_STATE(STATE_SENTINITIATE)
318 GET_STRING_OF_STATE(STATE_RECEIVEDINITIATE)
319 GET_STRING_OF_STATE(STATE_SENTPRACCEPT)
320 GET_STRING_OF_STATE(STATE_SENTACCEPT)
321 GET_STRING_OF_STATE(STATE_RECEIVEDPRACCEPT)
322 GET_STRING_OF_STATE(STATE_RECEIVEDACCEPT)
323 GET_STRING_OF_STATE(STATE_SENTMODIFY)
324 GET_STRING_OF_STATE(STATE_RECEIVEDMODIFY)
325 GET_STRING_OF_STATE(STATE_SENTREJECT)
326 GET_STRING_OF_STATE(STATE_RECEIVEDREJECT)
327 GET_STRING_OF_STATE(STATE_SENTREDIRECT)
328 GET_STRING_OF_STATE(STATE_SENTTERMINATE)
329 GET_STRING_OF_STATE(STATE_RECEIVEDTERMINATE)
330 GET_STRING_OF_STATE(STATE_INPROGRESS)
331 GET_STRING_OF_STATE(STATE_DEINIT)
332 default:
333 ASSERT(false);
334 break;
335 }
336 return result;
337}
338
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000339#define GET_STRING_OF_ERROR_CODE(err) \
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000340 case cricket::BaseSession::err: \
341 result = #err; \
342 break;
343
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000344static std::string GetErrorCodeString(cricket::BaseSession::Error err) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000345 std::string result;
346 switch (err) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000347 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
348 GET_STRING_OF_ERROR_CODE(ERROR_TIME)
349 GET_STRING_OF_ERROR_CODE(ERROR_RESPONSE)
350 GET_STRING_OF_ERROR_CODE(ERROR_NETWORK)
351 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
352 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000353 default:
354 ASSERT(false);
355 break;
356 }
357 return result;
358}
359
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000360static std::string MakeErrorString(const std::string& error,
361 const std::string& desc) {
362 std::ostringstream ret;
363 ret << error << " " << desc;
364 return ret.str();
365}
366
367static std::string MakeTdErrorString(const std::string& desc) {
368 return MakeErrorString(kPushDownTDFailed, desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000369}
370
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000371// Set |option| to the highest-priority value of |key| in the optional
372// constraints if the key is found and has a valid value.
373static void SetOptionFromOptionalConstraint(
374 const MediaConstraintsInterface* constraints,
375 const std::string& key, cricket::Settable<int>* option) {
376 if (!constraints) {
377 return;
378 }
379 std::string string_value;
380 int value;
381 if (constraints->GetOptional().FindFirst(key, &string_value)) {
382 if (talk_base::FromString(string_value, &value)) {
383 option->Set(value);
384 }
385 }
386}
387
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000388// Help class used to remember if a a remote peer has requested ice restart by
389// by sending a description with new ice ufrag and password.
390class IceRestartAnswerLatch {
391 public:
392 IceRestartAnswerLatch() : ice_restart_(false) { }
393
wu@webrtc.org91053e72013-08-10 07:18:04 +0000394 // Returns true if CheckForRemoteIceRestart has been called with a new session
395 // description where ice password and ufrag has changed since last time
396 // Reset() was called.
397 bool Get() const {
398 return ice_restart_;
399 }
400
401 void Reset() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000402 if (ice_restart_) {
403 ice_restart_ = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000404 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000405 }
406
407 void CheckForRemoteIceRestart(
408 const SessionDescriptionInterface* old_desc,
409 const SessionDescriptionInterface* new_desc) {
410 if (!old_desc || new_desc->type() != SessionDescriptionInterface::kOffer) {
411 return;
412 }
413 const SessionDescription* new_sd = new_desc->description();
414 const SessionDescription* old_sd = old_desc->description();
415 const ContentInfos& contents = new_sd->contents();
416 for (size_t index = 0; index < contents.size(); ++index) {
417 const ContentInfo* cinfo = &contents[index];
418 if (cinfo->rejected) {
419 continue;
420 }
421 // If the content isn't rejected, check if ufrag and password has
422 // changed.
423 const cricket::TransportDescription* new_transport_desc =
424 new_sd->GetTransportDescriptionByName(cinfo->name);
425 const cricket::TransportDescription* old_transport_desc =
426 old_sd->GetTransportDescriptionByName(cinfo->name);
427 if (!new_transport_desc || !old_transport_desc) {
428 // No transport description exist. This is not an ice restart.
429 continue;
430 }
431 if (new_transport_desc->ice_pwd != old_transport_desc->ice_pwd &&
432 new_transport_desc->ice_ufrag != old_transport_desc->ice_ufrag) {
433 LOG(LS_INFO) << "Remote peer request ice restart.";
434 ice_restart_ = true;
435 break;
436 }
437 }
438 }
439
440 private:
441 bool ice_restart_;
442};
443
wu@webrtc.org91053e72013-08-10 07:18:04 +0000444WebRtcSession::WebRtcSession(
445 cricket::ChannelManager* channel_manager,
446 talk_base::Thread* signaling_thread,
447 talk_base::Thread* worker_thread,
448 cricket::PortAllocator* port_allocator,
449 MediaStreamSignaling* mediastream_signaling)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000450 : cricket::BaseSession(signaling_thread, worker_thread, port_allocator,
451 talk_base::ToString(talk_base::CreateRandomId64() &
452 LLONG_MAX),
453 cricket::NS_JINGLE_RTP, false),
454 // RFC 3264: The numeric value of the session id and version in the
455 // o line MUST be representable with a "64 bit signed integer".
456 // Due to this constraint session id |sid_| is max limited to LLONG_MAX.
457 channel_manager_(channel_manager),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000458 mediastream_signaling_(mediastream_signaling),
459 ice_observer_(NULL),
460 ice_connection_state_(PeerConnectionInterface::kIceConnectionNew),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000461 older_version_remote_peer_(false),
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000462 dtls_enabled_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000463 data_channel_type_(cricket::DCT_NONE),
464 ice_restart_latch_(new IceRestartAnswerLatch) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000465}
466
467WebRtcSession::~WebRtcSession() {
468 if (voice_channel_.get()) {
469 SignalVoiceChannelDestroyed();
470 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
471 }
472 if (video_channel_.get()) {
473 SignalVideoChannelDestroyed();
474 channel_manager_->DestroyVideoChannel(video_channel_.release());
475 }
476 if (data_channel_.get()) {
477 SignalDataChannelDestroyed();
478 channel_manager_->DestroyDataChannel(data_channel_.release());
479 }
480 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
481 delete saved_candidates_[i];
482 }
483 delete identity();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000484}
485
wu@webrtc.org91053e72013-08-10 07:18:04 +0000486bool WebRtcSession::Initialize(
wu@webrtc.org97077a32013-10-25 21:18:33 +0000487 const PeerConnectionFactoryInterface::Options& options,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000488 const MediaConstraintsInterface* constraints,
489 DTLSIdentityServiceInterface* dtls_identity_service) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000490 // TODO(perkj): Take |constraints| into consideration. Return false if not all
491 // mandatory constraints can be fulfilled. Note that |constraints|
492 // can be null.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000493 bool value;
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000494
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000495 if (options.disable_encryption) {
496 dtls_enabled_ = false;
497 } else {
498 // Enable DTLS by default if |dtls_identity_service| is valid.
499 dtls_enabled_ = (dtls_identity_service != NULL);
500 // |constraints| can override the default |dtls_enabled_| value.
501 if (FindConstraint(
502 constraints,
503 MediaConstraintsInterface::kEnableDtlsSrtp,
504 &value, NULL)) {
505 dtls_enabled_ = value;
506 }
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000507 }
508
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000509 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000510 // It takes precendence over the disable_sctp_data_channels
511 // PeerConnectionFactoryInterface::Options.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000512 if (FindConstraint(
513 constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
514 &value, NULL) && value) {
515 LOG(LS_INFO) << "Allowing RTP data engine.";
516 data_channel_type_ = cricket::DCT_RTP;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000517 } else {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000518 // DTLS has to be enabled to use SCTP.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000519 if (!options.disable_sctp_data_channels && dtls_enabled_) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000520 LOG(LS_INFO) << "Allowing SCTP data engine.";
521 data_channel_type_ = cricket::DCT_SCTP;
522 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000523 }
524 if (data_channel_type_ != cricket::DCT_NONE) {
525 mediastream_signaling_->SetDataChannelFactory(this);
526 }
527
wu@webrtc.orgde305012013-10-31 15:40:38 +0000528 // Find DSCP constraint.
529 if (FindConstraint(
530 constraints,
531 MediaConstraintsInterface::kEnableDscp,
532 &value, NULL)) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +0000533 audio_options_.dscp.Set(value);
534 video_options_.dscp.Set(value);
535 }
536
537 // Find Suspend Below Min Bitrate constraint.
538 if (FindConstraint(
539 constraints,
540 MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate,
541 &value,
542 NULL)) {
543 video_options_.suspend_below_min_bitrate.Set(value);
wu@webrtc.orgde305012013-10-31 15:40:38 +0000544 }
545
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000546 if (FindConstraint(
547 constraints,
548 MediaConstraintsInterface::kSkipEncodingUnusedStreams,
549 &value,
550 NULL)) {
551 video_options_.skip_encoding_unused_streams.Set(value);
552 }
553
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000554 SetOptionFromOptionalConstraint(constraints,
555 MediaConstraintsInterface::kScreencastMinBitrate,
556 &video_options_.screencast_min_bitrate);
557
558 // Find constraints for cpu overuse detection.
559 SetOptionFromOptionalConstraint(constraints,
560 MediaConstraintsInterface::kCpuUnderuseThreshold,
561 &video_options_.cpu_underuse_threshold);
562 SetOptionFromOptionalConstraint(constraints,
563 MediaConstraintsInterface::kCpuOveruseThreshold,
564 &video_options_.cpu_overuse_threshold);
565
566 if (FindConstraint(
567 constraints,
568 MediaConstraintsInterface::kCpuOveruseDetection,
569 &value,
570 NULL)) {
571 video_options_.cpu_overuse_detection.Set(value);
572 }
573 if (FindConstraint(
574 constraints,
575 MediaConstraintsInterface::kCpuOveruseEncodeUsage,
576 &value,
577 NULL)) {
578 video_options_.cpu_overuse_encode_usage.Set(value);
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000579 }
580
581 // Find improved wifi bwe constraint.
582 if (FindConstraint(
583 constraints,
584 MediaConstraintsInterface::kImprovedWifiBwe,
585 &value,
586 NULL)) {
587 video_options_.use_improved_wifi_bandwidth_estimator.Set(value);
588 }
589
wu@webrtc.orgcfe5e9c2014-03-27 17:03:58 +0000590 if (FindConstraint(
591 constraints,
592 MediaConstraintsInterface::kHighStartBitrate,
593 &value,
594 NULL)) {
595 video_options_.video_start_bitrate.Set(cricket::kHighStartBitrate);
596 }
597
598 if (FindConstraint(
599 constraints,
600 MediaConstraintsInterface::kVeryHighBitrate,
601 &value,
602 NULL)) {
603 video_options_.video_highest_bitrate.Set(
604 cricket::VideoOptions::VERY_HIGH);
605 } else if (FindConstraint(
606 constraints,
607 MediaConstraintsInterface::kHighBitrate,
608 &value,
609 NULL)) {
610 video_options_.video_highest_bitrate.Set(
611 cricket::VideoOptions::HIGH);
612 }
613
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000614 const cricket::VideoCodec default_codec(
615 JsepSessionDescription::kDefaultVideoCodecId,
616 JsepSessionDescription::kDefaultVideoCodecName,
617 JsepSessionDescription::kMaxVideoCodecWidth,
618 JsepSessionDescription::kMaxVideoCodecHeight,
619 JsepSessionDescription::kDefaultVideoCodecFramerate,
620 JsepSessionDescription::kDefaultVideoCodecPreference);
621 channel_manager_->SetDefaultVideoEncoderConfig(
622 cricket::VideoEncoderConfig(default_codec));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000623
624 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
625 signaling_thread(),
626 channel_manager_,
627 mediastream_signaling_,
628 dtls_identity_service,
629 this,
630 id(),
631 data_channel_type_,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000632 dtls_enabled_));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000633
634 webrtc_session_desc_factory_->SignalIdentityReady.connect(
635 this, &WebRtcSession::OnIdentityReady);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000636
wu@webrtc.org97077a32013-10-25 21:18:33 +0000637 if (options.disable_encryption) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000638 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000639 }
640
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000641 return true;
642}
643
644void WebRtcSession::Terminate() {
645 SetState(STATE_RECEIVEDTERMINATE);
646 RemoveUnusedChannelsAndTransports(NULL);
647 ASSERT(voice_channel_.get() == NULL);
648 ASSERT(video_channel_.get() == NULL);
649 ASSERT(data_channel_.get() == NULL);
650}
651
652bool WebRtcSession::StartCandidatesAllocation() {
653 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
654 // from TransportProxy to start gathering ice candidates.
655 SpeculativelyConnectAllTransportChannels();
656 if (!saved_candidates_.empty()) {
657 // If there are saved candidates which arrived before local description is
658 // set, copy those to remote description.
659 CopySavedCandidates(remote_desc_.get());
660 }
661 // Push remote candidates present in remote description to transport channels.
662 UseCandidatesInSessionDescription(remote_desc_.get());
663 return true;
664}
665
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000666void WebRtcSession::SetSdesPolicy(cricket::SecurePolicy secure_policy) {
667 webrtc_session_desc_factory_->SetSdesPolicy(secure_policy);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000668}
669
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000670cricket::SecurePolicy WebRtcSession::SdesPolicy() const {
671 return webrtc_session_desc_factory_->SdesPolicy();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000672}
673
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000674bool WebRtcSession::GetSslRole(talk_base::SSLRole* role) {
675 if (local_description() == NULL || remote_description() == NULL) {
676 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
677 << "SSL Role of the session.";
678 return false;
679 }
680
681 // TODO(mallinath) - Return role of each transport, as role may differ from
682 // one another.
683 // In current implementaion we just return the role of first transport in the
684 // transport map.
685 for (cricket::TransportMap::const_iterator iter = transport_proxies().begin();
686 iter != transport_proxies().end(); ++iter) {
687 if (iter->second->impl()) {
688 return iter->second->impl()->GetSslRole(role);
689 }
690 }
691 return false;
692}
693
wu@webrtc.org91053e72013-08-10 07:18:04 +0000694void WebRtcSession::CreateOffer(CreateSessionDescriptionObserver* observer,
695 const MediaConstraintsInterface* constraints) {
696 webrtc_session_desc_factory_->CreateOffer(observer, constraints);
697}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000698
wu@webrtc.org91053e72013-08-10 07:18:04 +0000699void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
700 const MediaConstraintsInterface* constraints) {
701 webrtc_session_desc_factory_->CreateAnswer(observer, constraints);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000702}
703
704bool WebRtcSession::SetLocalDescription(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
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000709 // Validate SDP.
710 if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
711 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000712 }
713
714 // Update the initiator flag if this session is the initiator.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000715 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716 if (state() == STATE_INIT && action == kOffer) {
717 set_initiator(true);
718 }
719
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000720 cricket::SecurePolicy sdes_policy =
721 webrtc_session_desc_factory_->SdesPolicy();
722 cricket::CryptoType crypto_required = dtls_enabled_ ?
723 cricket::CT_DTLS : (sdes_policy == cricket::SEC_REQUIRED ?
724 cricket::CT_SDES : cricket::CT_NONE);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000725 // Update the MediaContentDescription crypto settings as per the policy set.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000726 UpdateSessionDescriptionSecurePolicy(crypto_required, desc->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727
728 set_local_description(desc->description()->Copy());
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000729 local_desc_.reset(desc_temp.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730
731 // Transport and Media channels will be created only when offer is set.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000732 if (action == kOffer && !CreateChannels(local_desc_->description())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733 // TODO(mallinath) - Handle CreateChannel failure, as new local description
734 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000735 return BadLocalSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000736 }
737
738 // Remove channel and transport proxies, if MediaContentDescription is
739 // rejected.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000740 RemoveUnusedChannelsAndTransports(local_desc_->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000741
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000742 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000743 return false;
744 }
745 // Kick starting the ice candidates allocation.
746 StartCandidatesAllocation();
747
748 // Update state and SSRC of local MediaStreams and DataChannels based on the
749 // local session description.
750 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
751
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000752 talk_base::SSLRole role;
753 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
754 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
755 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000757 return BadLocalSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000758 }
759 return true;
760}
761
762bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
763 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000764 // Takes the ownership of |desc| regardless of the result.
765 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
766
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000767 // Validate SDP.
768 if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
769 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000770 }
771
772 // Transport and Media channels will be created only when offer is set.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000773 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000774 if (action == kOffer && !CreateChannels(desc->description())) {
775 // TODO(mallinath) - Handle CreateChannel failure, as new local description
776 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000777 return BadRemoteSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000778 }
779
780 // Remove channel and transport proxies, if MediaContentDescription is
781 // rejected.
782 RemoveUnusedChannelsAndTransports(desc->description());
783
784 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
785 // is called.
786 set_remote_description(desc->description()->Copy());
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000787 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000788 return false;
789 }
790
791 // Update remote MediaStreams.
792 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
793 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000794 return BadRemoteSdp(desc->type(), kInvalidCandidates, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000795 }
796
797 // Copy all saved candidates.
798 CopySavedCandidates(desc);
799 // We retain all received candidates.
wu@webrtc.org91053e72013-08-10 07:18:04 +0000800 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
801 remote_desc_.get(), desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000802 // Check if this new SessionDescription contains new ice ufrag and password
803 // that indicates the remote peer requests ice restart.
804 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(),
805 desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000806 remote_desc_.reset(desc_temp.release());
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000807
808 talk_base::SSLRole role;
809 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
810 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
811 }
812
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000813 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000814 return BadRemoteSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000815 }
816 return true;
817}
818
819bool WebRtcSession::UpdateSessionState(
820 Action action, cricket::ContentSource source,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000821 std::string* err_desc) {
822 // If there's already a pending error then no state transition should happen.
823 // But all call-sites should be verifying this before calling us!
824 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000825 std::string td_err;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826 if (action == kOffer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000827 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
828 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000829 }
830 SetState(source == cricket::CS_LOCAL ?
831 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
832 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000833 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000834 }
835 } else if (action == kPrAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000836 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
837 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000838 }
839 EnableChannels();
840 SetState(source == cricket::CS_LOCAL ?
841 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
842 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000843 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000844 }
845 } else if (action == kAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000846 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
847 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000848 }
849 MaybeEnableMuxingSupport();
850 EnableChannels();
851 SetState(source == cricket::CS_LOCAL ?
852 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
853 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000854 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000855 }
856 }
857 return true;
858}
859
860WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
861 if (type == SessionDescriptionInterface::kOffer) {
862 return WebRtcSession::kOffer;
863 } else if (type == SessionDescriptionInterface::kPrAnswer) {
864 return WebRtcSession::kPrAnswer;
865 } else if (type == SessionDescriptionInterface::kAnswer) {
866 return WebRtcSession::kAnswer;
867 }
868 ASSERT(false && "unknown action type");
869 return WebRtcSession::kOffer;
870}
871
872bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
873 if (state() == STATE_INIT) {
874 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
875 << "without any offer (local or remote) "
876 << "session description.";
877 return false;
878 }
879
880 if (!candidate) {
881 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
882 return false;
883 }
884
buildbot@webrtc.org61c1b8e2014-04-09 06:06:38 +0000885 cricket::TransportProxy* transport_proxy = NULL;
886 if (remote_description()) {
887 size_t mediacontent_index =
888 static_cast<size_t>(candidate->sdp_mline_index());
889 size_t remote_content_size =
890 BaseSession::remote_description()->contents().size();
891 if (mediacontent_index >= remote_content_size) {
892 LOG(LS_ERROR)
893 << "ProcessIceMessage: Invalid candidate media index.";
894 return false;
895 }
896
897 cricket::ContentInfo content =
898 BaseSession::remote_description()->contents()[mediacontent_index];
899 transport_proxy = GetTransportProxy(content.name);
900 }
901
902 // We need to check the local/remote description for the Transport instead of
903 // the session, because a new Transport added during renegotiation may have
904 // them unset while the session has them set from the previou negotiation. Not
905 // doing so may trigger the auto generation of transport description and mess
906 // up DTLS identity information, ICE credential, etc.
907 if (!transport_proxy || !(transport_proxy->local_description_set() &&
908 transport_proxy->remote_description_set())) {
909 LOG(LS_INFO) << "ProcessIceMessage: Local/Remote description not set "
910 << "on the Transport, save the candidate for later use.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000911 saved_candidates_.push_back(
912 new JsepIceCandidate(candidate->sdp_mid(), candidate->sdp_mline_index(),
913 candidate->candidate()));
914 return true;
915 }
916
917 // Add this candidate to the remote session description.
918 if (!remote_desc_->AddCandidate(candidate)) {
919 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
920 return false;
921 }
922
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000923 return UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000924}
925
926bool WebRtcSession::GetTrackIdBySsrc(uint32 ssrc, std::string* id) {
927 if (GetLocalTrackId(ssrc, id)) {
928 if (GetRemoteTrackId(ssrc, id)) {
929 LOG(LS_WARNING) << "SSRC " << ssrc
930 << " exists in both local and remote descriptions";
931 return true; // We return the remote track id.
932 }
933 return true;
934 } else {
935 return GetRemoteTrackId(ssrc, id);
936 }
937}
938
939bool WebRtcSession::GetLocalTrackId(uint32 ssrc, std::string* track_id) {
940 if (!BaseSession::local_description())
941 return false;
942 return webrtc::GetTrackIdBySsrc(
943 BaseSession::local_description(), ssrc, track_id);
944}
945
946bool WebRtcSession::GetRemoteTrackId(uint32 ssrc, std::string* track_id) {
947 if (!BaseSession::remote_description())
948 return false;
949 return webrtc::GetTrackIdBySsrc(
950 BaseSession::remote_description(), ssrc, track_id);
951}
952
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000953std::string WebRtcSession::BadStateErrMsg(State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954 std::ostringstream desc;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000955 desc << "Called in wrong state: " << GetStateString(state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956 return desc.str();
957}
958
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000959void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable,
960 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000961 ASSERT(signaling_thread()->IsCurrent());
962 if (!voice_channel_) {
963 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
964 return;
965 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000966 if (!voice_channel_->SetRemoteRenderer(ssrc, renderer)) {
967 // SetRenderer() can fail if the ssrc does not match any playout channel.
968 LOG(LS_ERROR) << "SetAudioPlayout: ssrc is incorrect: " << ssrc;
969 return;
970 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000971 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
972 // Allow that SetOutputScaling fail if |enable| is false but assert
973 // otherwise. This in the normal case when the underlying media channel has
974 // already been deleted.
975 ASSERT(enable == false);
976 }
977}
978
979void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000980 const cricket::AudioOptions& options,
981 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000982 ASSERT(signaling_thread()->IsCurrent());
983 if (!voice_channel_) {
984 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
985 return;
986 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000987 if (!voice_channel_->SetLocalRenderer(ssrc, renderer)) {
988 // SetRenderer() can fail if the ssrc does not match any send channel.
989 LOG(LS_ERROR) << "SetAudioSend: ssrc is incorrect: " << ssrc;
990 return;
991 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000992 if (!voice_channel_->MuteStream(ssrc, !enable)) {
993 // Allow that MuteStream fail if |enable| is false but assert otherwise.
994 // This in the normal case when the underlying media channel has already
995 // been deleted.
996 ASSERT(enable == false);
997 return;
998 }
999 if (enable)
1000 voice_channel_->SetChannelOptions(options);
1001}
1002
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001003void WebRtcSession::SetAudioPlayoutVolume(uint32 ssrc, double volume) {
1004 ASSERT(signaling_thread()->IsCurrent());
1005 ASSERT(volume >= 0 && volume <= 10);
1006 if (!voice_channel_) {
1007 LOG(LS_ERROR) << "SetAudioPlayoutVolume: No audio channel exists.";
1008 return;
1009 }
1010
1011 if (!voice_channel_->SetOutputScaling(ssrc, volume, volume))
1012 ASSERT(false);
1013}
1014
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
1016 cricket::VideoCapturer* camera) {
1017 ASSERT(signaling_thread()->IsCurrent());
1018
1019 if (!video_channel_.get()) {
1020 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
1021 // support video.
1022 LOG(LS_WARNING) << "Video not used in this call.";
1023 return false;
1024 }
1025 if (!video_channel_->SetCapturer(ssrc, camera)) {
1026 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
1027 // This in the normal case when the underlying media channel has already
1028 // been deleted.
1029 ASSERT(camera == NULL);
1030 return false;
1031 }
1032 return true;
1033}
1034
1035void WebRtcSession::SetVideoPlayout(uint32 ssrc,
1036 bool enable,
1037 cricket::VideoRenderer* renderer) {
1038 ASSERT(signaling_thread()->IsCurrent());
1039 if (!video_channel_) {
1040 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
1041 return;
1042 }
1043 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
1044 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
1045 // This in the normal case when the underlying media channel has already
1046 // been deleted.
1047 ASSERT(renderer == NULL);
1048 }
1049}
1050
1051void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
1052 const cricket::VideoOptions* options) {
1053 ASSERT(signaling_thread()->IsCurrent());
1054 if (!video_channel_) {
1055 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
1056 return;
1057 }
1058 if (!video_channel_->MuteStream(ssrc, !enable)) {
1059 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1060 // This in the normal case when the underlying media channel has already
1061 // been deleted.
1062 ASSERT(enable == false);
1063 return;
1064 }
1065 if (enable && options)
1066 video_channel_->SetChannelOptions(*options);
1067}
1068
1069bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
1070 ASSERT(signaling_thread()->IsCurrent());
1071 if (!voice_channel_) {
1072 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
1073 return false;
1074 }
1075 uint32 send_ssrc = 0;
1076 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
1077 // exists.
1078 if (!GetAudioSsrcByTrackId(BaseSession::local_description(), track_id,
1079 &send_ssrc)) {
1080 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1081 return false;
1082 }
1083 return voice_channel_->CanInsertDtmf();
1084}
1085
1086bool WebRtcSession::InsertDtmf(const std::string& track_id,
1087 int code, int duration) {
1088 ASSERT(signaling_thread()->IsCurrent());
1089 if (!voice_channel_) {
1090 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1091 return false;
1092 }
1093 uint32 send_ssrc = 0;
1094 if (!VERIFY(GetAudioSsrcByTrackId(BaseSession::local_description(),
1095 track_id, &send_ssrc))) {
1096 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1097 return false;
1098 }
1099 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1100 cricket::DF_SEND)) {
1101 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1102 return false;
1103 }
1104 return true;
1105}
1106
1107sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1108 return &SignalVoiceChannelDestroyed;
1109}
1110
wu@webrtc.org78187522013-10-07 23:32:02 +00001111bool WebRtcSession::SendData(const cricket::SendDataParams& params,
1112 const talk_base::Buffer& payload,
1113 cricket::SendDataResult* result) {
1114 if (!data_channel_.get()) {
1115 LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
1116 return false;
1117 }
1118 return data_channel_->SendData(params, payload, result);
1119}
1120
1121bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
1122 if (!data_channel_.get()) {
1123 LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
1124 return false;
1125 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001126 data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
1127 &DataChannel::OnChannelReady);
1128 data_channel_->SignalDataReceived.connect(webrtc_data_channel,
1129 &DataChannel::OnDataReceived);
wu@webrtc.org78187522013-10-07 23:32:02 +00001130 return true;
1131}
1132
1133void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001134 if (!data_channel_.get()) {
1135 LOG(LS_ERROR) << "DisconnectDataChannel called when data_channel_ is NULL.";
1136 return;
1137 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001138 data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
1139 data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
1140}
1141
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001142void WebRtcSession::AddSctpDataStream(uint32 sid) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001143 if (!data_channel_.get()) {
1144 LOG(LS_ERROR) << "AddDataChannelStreams called when data_channel_ is NULL.";
1145 return;
1146 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001147 data_channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(sid));
1148 data_channel_->AddSendStream(cricket::StreamParams::CreateLegacy(sid));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001149}
1150
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001151void WebRtcSession::RemoveSctpDataStream(uint32 sid) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001152 if (!data_channel_.get()) {
1153 LOG(LS_ERROR) << "RemoveDataChannelStreams called when data_channel_ is "
1154 << "NULL.";
1155 return;
1156 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001157 data_channel_->RemoveRecvStream(sid);
1158 data_channel_->RemoveSendStream(sid);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001159}
1160
wu@webrtc.org07a6fbe2013-11-04 18:41:34 +00001161bool WebRtcSession::ReadyToSendData() const {
1162 return data_channel_.get() && data_channel_->ready_to_send_data();
1163}
1164
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165talk_base::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
wu@webrtc.org78187522013-10-07 23:32:02 +00001166 const std::string& label,
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001167 const InternalDataChannelInit* config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001168 if (state() == STATE_RECEIVEDTERMINATE) {
1169 return NULL;
1170 }
1171 if (data_channel_type_ == cricket::DCT_NONE) {
1172 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1173 return NULL;
1174 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001175 InternalDataChannelInit new_config =
1176 config ? (*config) : InternalDataChannelInit();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001177 if (data_channel_type_ == cricket::DCT_SCTP) {
1178 if (new_config.id < 0) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001179 talk_base::SSLRole role;
1180 if (GetSslRole(&role) &&
1181 !mediastream_signaling_->AllocateSctpSid(role, &new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001182 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1183 return NULL;
1184 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001185 } else if (!mediastream_signaling_->IsSctpSidAvailable(new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001186 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1187 << "because the id is already in use or out of range.";
1188 return NULL;
1189 }
1190 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001191
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001192 talk_base::scoped_refptr<DataChannel> channel(DataChannel::Create(
1193 this, data_channel_type_, label, new_config));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001194 if (channel && !mediastream_signaling_->AddDataChannel(channel))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001195 return NULL;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001196
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197 return channel;
1198}
1199
1200cricket::DataChannelType WebRtcSession::data_channel_type() const {
1201 return data_channel_type_;
1202}
1203
wu@webrtc.org91053e72013-08-10 07:18:04 +00001204bool WebRtcSession::IceRestartPending() const {
1205 return ice_restart_latch_->Get();
1206}
1207
1208void WebRtcSession::ResetIceRestartLatch() {
1209 ice_restart_latch_->Reset();
1210}
1211
1212void WebRtcSession::OnIdentityReady(talk_base::SSLIdentity* identity) {
1213 SetIdentity(identity);
1214}
1215
1216bool WebRtcSession::waiting_for_identity() const {
1217 return webrtc_session_desc_factory_->waiting_for_identity();
1218}
1219
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001220void WebRtcSession::SetIceConnectionState(
1221 PeerConnectionInterface::IceConnectionState state) {
1222 if (ice_connection_state_ == state) {
1223 return;
1224 }
1225
1226 // ASSERT that the requested transition is allowed. Note that
1227 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1228 // within PeerConnection). This switch statement should compile away when
1229 // ASSERTs are disabled.
1230 switch (ice_connection_state_) {
1231 case PeerConnectionInterface::kIceConnectionNew:
1232 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1233 break;
1234 case PeerConnectionInterface::kIceConnectionChecking:
1235 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1236 state == PeerConnectionInterface::kIceConnectionConnected);
1237 break;
1238 case PeerConnectionInterface::kIceConnectionConnected:
1239 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1240 state == PeerConnectionInterface::kIceConnectionChecking ||
1241 state == PeerConnectionInterface::kIceConnectionCompleted);
1242 break;
1243 case PeerConnectionInterface::kIceConnectionCompleted:
1244 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1245 state == PeerConnectionInterface::kIceConnectionDisconnected);
1246 break;
1247 case PeerConnectionInterface::kIceConnectionFailed:
1248 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1249 break;
1250 case PeerConnectionInterface::kIceConnectionDisconnected:
1251 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1252 state == PeerConnectionInterface::kIceConnectionConnected ||
1253 state == PeerConnectionInterface::kIceConnectionCompleted ||
1254 state == PeerConnectionInterface::kIceConnectionFailed);
1255 break;
1256 case PeerConnectionInterface::kIceConnectionClosed:
1257 ASSERT(false);
1258 break;
1259 default:
1260 ASSERT(false);
1261 break;
1262 }
1263
1264 ice_connection_state_ = state;
1265 if (ice_observer_) {
1266 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1267 }
1268}
1269
1270void WebRtcSession::OnTransportRequestSignaling(
1271 cricket::Transport* transport) {
1272 ASSERT(signaling_thread()->IsCurrent());
1273 transport->OnSignalingReady();
1274 if (ice_observer_) {
1275 ice_observer_->OnIceGatheringChange(
1276 PeerConnectionInterface::kIceGatheringGathering);
1277 }
1278}
1279
1280void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1281 ASSERT(signaling_thread()->IsCurrent());
1282 // start monitoring for the write state of the transport.
1283 OnTransportWritable(transport);
1284}
1285
1286void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1287 ASSERT(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001288 if (transport->all_channels_writable()) {
henrike@webrtc.org05376342014-03-10 15:53:12 +00001289 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001290 } else if (transport->HasChannels()) {
1291 // If the current state is Connected or Completed, then there were writable
1292 // channels but now there are not, so the next state must be Disconnected.
1293 if (ice_connection_state_ ==
1294 PeerConnectionInterface::kIceConnectionConnected ||
1295 ice_connection_state_ ==
1296 PeerConnectionInterface::kIceConnectionCompleted) {
1297 SetIceConnectionState(
1298 PeerConnectionInterface::kIceConnectionDisconnected);
1299 }
1300 }
1301}
1302
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001303void WebRtcSession::OnTransportCompleted(cricket::Transport* transport) {
1304 ASSERT(signaling_thread()->IsCurrent());
1305 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
1306}
1307
1308void WebRtcSession::OnTransportFailed(cricket::Transport* transport) {
1309 ASSERT(signaling_thread()->IsCurrent());
1310 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
1311}
1312
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313void WebRtcSession::OnTransportProxyCandidatesReady(
1314 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1315 ASSERT(signaling_thread()->IsCurrent());
1316 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1317}
1318
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001319void WebRtcSession::OnCandidatesAllocationDone() {
1320 ASSERT(signaling_thread()->IsCurrent());
1321 if (ice_observer_) {
1322 ice_observer_->OnIceGatheringChange(
1323 PeerConnectionInterface::kIceGatheringComplete);
1324 ice_observer_->OnIceComplete();
1325 }
1326}
1327
1328// Enabling voice and video channel.
1329void WebRtcSession::EnableChannels() {
1330 if (voice_channel_ && !voice_channel_->enabled())
1331 voice_channel_->Enable(true);
1332
1333 if (video_channel_ && !video_channel_->enabled())
1334 video_channel_->Enable(true);
1335
1336 if (data_channel_.get() && !data_channel_->enabled())
1337 data_channel_->Enable(true);
1338}
1339
1340void WebRtcSession::ProcessNewLocalCandidate(
1341 const std::string& content_name,
1342 const cricket::Candidates& candidates) {
1343 int sdp_mline_index;
1344 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1345 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1346 << content_name << " not found";
1347 return;
1348 }
1349
1350 for (cricket::Candidates::const_iterator citer = candidates.begin();
1351 citer != candidates.end(); ++citer) {
1352 // Use content_name as the candidate media id.
1353 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1354 if (ice_observer_) {
1355 ice_observer_->OnIceCandidate(&candidate);
1356 }
1357 if (local_desc_) {
1358 local_desc_->AddCandidate(&candidate);
1359 }
1360 }
1361}
1362
1363// Returns the media index for a local ice candidate given the content name.
1364bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1365 int* sdp_mline_index) {
1366 if (!BaseSession::local_description() || !sdp_mline_index)
1367 return false;
1368
1369 bool content_found = false;
1370 const ContentInfos& contents = BaseSession::local_description()->contents();
1371 for (size_t index = 0; index < contents.size(); ++index) {
1372 if (contents[index].name == content_name) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001373 *sdp_mline_index = static_cast<int>(index);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001374 content_found = true;
1375 break;
1376 }
1377 }
1378 return content_found;
1379}
1380
1381bool WebRtcSession::UseCandidatesInSessionDescription(
1382 const SessionDescriptionInterface* remote_desc) {
1383 if (!remote_desc)
1384 return true;
1385 bool ret = true;
1386 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1387 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1388 for (size_t n = 0; n < candidates->count(); ++n) {
1389 ret = UseCandidate(candidates->at(n));
1390 if (!ret)
1391 break;
1392 }
1393 }
1394 return ret;
1395}
1396
1397bool WebRtcSession::UseCandidate(
1398 const IceCandidateInterface* candidate) {
1399
1400 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
1401 size_t remote_content_size =
1402 BaseSession::remote_description()->contents().size();
1403 if (mediacontent_index >= remote_content_size) {
1404 LOG(LS_ERROR)
1405 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1406 return false;
1407 }
1408
1409 cricket::ContentInfo content =
1410 BaseSession::remote_description()->contents()[mediacontent_index];
1411 std::vector<cricket::Candidate> candidates;
1412 candidates.push_back(candidate->candidate());
1413 // Invoking BaseSession method to handle remote candidates.
1414 std::string error;
1415 if (OnRemoteCandidates(content.name, candidates, &error)) {
1416 // Candidates successfully submitted for checking.
1417 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1418 ice_connection_state_ ==
1419 PeerConnectionInterface::kIceConnectionDisconnected) {
1420 // If state is New, then the session has just gotten its first remote ICE
1421 // candidates, so go to Checking.
1422 // If state is Disconnected, the session is re-using old candidates or
1423 // receiving additional ones, so go to Checking.
1424 // If state is Connected, stay Connected.
1425 // TODO(bemasc): If state is Connected, and the new candidates are for a
1426 // newly added transport, then the state actually _should_ move to
1427 // checking. Add a way to distinguish that case.
1428 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1429 }
1430 // TODO(bemasc): If state is Completed, go back to Connected.
1431 } else {
fischman@webrtc.org4f2bd682014-03-28 18:13:34 +00001432 if (!error.empty()) {
1433 LOG(LS_WARNING) << error;
1434 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001435 }
1436 return true;
1437}
1438
1439void WebRtcSession::RemoveUnusedChannelsAndTransports(
1440 const SessionDescription* desc) {
1441 const cricket::ContentInfo* voice_info =
1442 cricket::GetFirstAudioContent(desc);
1443 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1444 mediastream_signaling_->OnAudioChannelClose();
1445 SignalVoiceChannelDestroyed();
1446 const std::string content_name = voice_channel_->content_name();
1447 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
1448 DestroyTransportProxy(content_name);
1449 }
1450
1451 const cricket::ContentInfo* video_info =
1452 cricket::GetFirstVideoContent(desc);
1453 if ((!video_info || video_info->rejected) && video_channel_) {
1454 mediastream_signaling_->OnVideoChannelClose();
1455 SignalVideoChannelDestroyed();
1456 const std::string content_name = video_channel_->content_name();
1457 channel_manager_->DestroyVideoChannel(video_channel_.release());
1458 DestroyTransportProxy(content_name);
1459 }
1460
1461 const cricket::ContentInfo* data_info =
1462 cricket::GetFirstDataContent(desc);
1463 if ((!data_info || data_info->rejected) && data_channel_) {
1464 mediastream_signaling_->OnDataChannelClose();
1465 SignalDataChannelDestroyed();
1466 const std::string content_name = data_channel_->content_name();
1467 channel_manager_->DestroyDataChannel(data_channel_.release());
1468 DestroyTransportProxy(content_name);
1469 }
1470}
1471
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001472// TODO(mallinath) - Add a correct error code if the channels are not creatued
1473// due to BUNDLE is enabled but rtcp-mux is disabled.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001474bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
1475 // Disabling the BUNDLE flag in PortAllocator if offer disabled it.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001476 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1477 if (state() == STATE_INIT && !bundle_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001478 port_allocator()->set_flags(port_allocator()->flags() &
1479 ~cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1480 }
1481
1482 // Creating the media channels and transport proxies.
1483 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1484 if (voice && !voice->rejected && !voice_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001485 if (!CreateVoiceChannel(voice)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001486 LOG(LS_ERROR) << "Failed to create voice channel.";
1487 return false;
1488 }
1489 }
1490
1491 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1492 if (video && !video->rejected && !video_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001493 if (!CreateVideoChannel(video)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001494 LOG(LS_ERROR) << "Failed to create video channel.";
1495 return false;
1496 }
1497 }
1498
1499 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1500 if (data_channel_type_ != cricket::DCT_NONE &&
1501 data && !data->rejected && !data_channel_.get()) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001502 if (!CreateDataChannel(data)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001503 LOG(LS_ERROR) << "Failed to create data channel.";
1504 return false;
1505 }
1506 }
1507
1508 return true;
1509}
1510
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001511bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001512 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001513 this, content->name, true));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001514 if (!voice_channel_.get())
1515 return false;
1516
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001517 voice_channel_->SetChannelOptions(audio_options_);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001518 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001519}
1520
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001521bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001522 video_channel_.reset(channel_manager_->CreateVideoChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001523 this, content->name, true, voice_channel_.get()));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001524 if (!video_channel_.get())
1525 return false;
1526
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001527 video_channel_->SetChannelOptions(video_options_);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001528 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001529}
1530
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001531bool WebRtcSession::CreateDataChannel(const cricket::ContentInfo* content) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001532 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001533 data_channel_.reset(channel_manager_->CreateDataChannel(
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001534 this, content->name, !sctp, data_channel_type_));
wu@webrtc.org91053e72013-08-10 07:18:04 +00001535 if (!data_channel_.get()) {
1536 return false;
1537 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001538 if (sctp) {
1539 mediastream_signaling_->OnDataTransportCreatedForSctp();
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001540 data_channel_->SignalDataReceived.connect(
1541 this, &WebRtcSession::OnDataChannelMessageReceived);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001542 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001543 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001544}
1545
1546void WebRtcSession::CopySavedCandidates(
1547 SessionDescriptionInterface* dest_desc) {
1548 if (!dest_desc) {
1549 ASSERT(false);
1550 return;
1551 }
1552 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1553 dest_desc->AddCandidate(saved_candidates_[i]);
1554 delete saved_candidates_[i];
1555 }
1556 saved_candidates_.clear();
1557}
1558
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001559void WebRtcSession::OnDataChannelMessageReceived(
1560 cricket::DataChannel* channel,
1561 const cricket::ReceiveDataParams& params,
1562 const talk_base::Buffer& payload) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001563 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001564 if (params.type == cricket::DMT_CONTROL &&
1565 mediastream_signaling_->IsSctpSidAvailable(params.ssrc)) {
1566 // Received CONTROL on unused sid, process as an OPEN message.
1567 mediastream_signaling_->AddDataChannelFromOpenMessage(params, payload);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001568 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001569 // otherwise ignore the message.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001570}
1571
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001572// Returns false if bundle is enabled and rtcp_mux is disabled.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001573bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001574 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1575 if (!bundle_enabled)
1576 return true;
1577
1578 const cricket::ContentGroup* bundle_group =
1579 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1580 ASSERT(bundle_group != NULL);
1581
1582 const cricket::ContentInfos& contents = desc->contents();
1583 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1584 citer != contents.end(); ++citer) {
1585 const cricket::ContentInfo* content = (&*citer);
1586 ASSERT(content != NULL);
1587 if (bundle_group->HasContentName(content->name) &&
1588 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1589 if (!HasRtcpMuxEnabled(content))
1590 return false;
1591 }
1592 }
1593 // RTCP-MUX is enabled in all the contents.
1594 return true;
1595}
1596
1597bool WebRtcSession::HasRtcpMuxEnabled(
1598 const cricket::ContentInfo* content) {
1599 const cricket::MediaContentDescription* description =
1600 static_cast<cricket::MediaContentDescription*>(content->description);
1601 return description->rtcp_mux();
1602}
1603
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001604bool WebRtcSession::ValidateSessionDescription(
1605 const SessionDescriptionInterface* sdesc,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001606 cricket::ContentSource source, std::string* err_desc) {
1607 std::string type;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001608 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001609 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001610 }
1611
1612 if (!sdesc || !sdesc->description()) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001613 return BadSdp(source, type, kInvalidSdp, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001614 }
1615
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001616 type = sdesc->type();
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001617 Action action = GetAction(sdesc->type());
1618 if (source == cricket::CS_LOCAL) {
1619 if (!ExpectSetLocalDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001620 return BadLocalSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001621 } else {
1622 if (!ExpectSetRemoteDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001623 return BadRemoteSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001624 }
1625
1626 // Verify crypto settings.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001627 std::string crypto_error;
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +00001628 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
1629 dtls_enabled_) &&
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001630 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001631 return BadSdp(source, type, crypto_error, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001632 }
1633
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001634 // Verify ice-ufrag and ice-pwd.
1635 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001636 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001637 }
1638
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001639 if (!ValidateBundleSettings(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001640 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001641 }
1642
1643 // Verify m-lines in Answer when compared against Offer.
1644 if (action == kAnswer) {
1645 const cricket::SessionDescription* offer_desc =
1646 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1647 local_description()->description();
1648 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001649 return BadAnswerSdp(source, kMlineMismatch, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001650 }
1651 }
1652
1653 return true;
1654}
1655
1656bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1657 return ((action == kOffer && state() == STATE_INIT) ||
1658 // update local offer
1659 (action == kOffer && state() == STATE_SENTINITIATE) ||
1660 // update the current ongoing session.
1661 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1662 (action == kOffer && state() == STATE_SENTACCEPT) ||
1663 (action == kOffer && state() == STATE_INPROGRESS) ||
1664 // accept remote offer
1665 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1666 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1667 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1668 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1669}
1670
1671bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1672 return ((action == kOffer && state() == STATE_INIT) ||
1673 // update remote offer
1674 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1675 // update the current ongoing session
1676 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1677 (action == kOffer && state() == STATE_SENTACCEPT) ||
1678 (action == kOffer && state() == STATE_INPROGRESS) ||
1679 // accept local offer
1680 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1681 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1682 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1683 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1684}
1685
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001686std::string WebRtcSession::GetSessionErrorMsg() {
1687 std::ostringstream desc;
1688 desc << kSessionError << GetErrorCodeString(error()) << ". ";
1689 desc << kSessionErrorDesc << error_desc() << ".";
1690 return desc.str();
1691}
1692
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001693} // namespace webrtc